#!/usr/bin/env ruby

#Licensed to the Apache Software Foundation (ASF) under one or more contributor
#license agreements.  See the NOTICE.txt file distributed with this work for
#additional information regarding copyright ownership.  The ASF licenses this
#file to you under the Apache License, Version 2.0 (the "License"); you may not
#use this file except in compliance with the License.  You may obtain a copy of
#the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
#License for the specific language governing permissions and limitations under
#the License.

require 'gli'
require 'yaml'
require 'usergrid_iron'
require 'highline/import'
require 'command_line_reporter'
include CommandLineReporter
require 'ugc'
include GLI::App

program_desc 'Usergrid Command Line'
version Ugc::VERSION

desc 'verbose'
switch [:v,:verbose], negatable: false

desc 'management'
switch [:m,:management], negatable: false

desc 'show curl equivalent (does not execute)'
switch [:c,:curl], negatable: false

desc 'draw table border'
default_value true
switch [:border]

desc 'settings directory'
arg_name 'settings directory'
default_value File.join(ENV['HOME'], '.ugc')
flag [:s,:settings]

# load helpers && commands
commands_from '../lib/ugc/helpers'
commands_from '../lib/ugc/commands'

pre do |global_options,command,options,args|
  if global_options[:verbose]
    RestClient.log=Logger.new(STDOUT)
  else
    Usergrid::LOG.level = Logger::WARN
  end

  $settings = Ugc::Settings.new global_options
  if not $settings.configured?
    raise "not configured" unless command.name == :profile or command.parent.name == :target
    true
  elsif command.name == :login
    true
  else
    $application = Ugc::Application.new
    $management = Ugc::Management.new
    $context = global_options[:management] ? $management : $application
    true
  end
end

post do |global_options,command,options,args|
  # post-run logic here
end

on_error do |e|
  # return false to skip default error handling
  if e.is_a? RestClient::Exception
    begin
      puts "#{e.http_code} error: #{e.response.data['error_description']}"
      if e.http_code == 401 and not $settings.logged_in?
        puts "(Hint: You may need to log in.)"
      end
    rescue MultiJson::DecodeError
      puts e.response
    end
    false
  else
    true
  end
end

exit run(ARGV)
