#!/usr/bin/ruby

require "bughunting/common"
require "bughunting/client/controller"
require "bughunting/client/error"

client_config = "/etc/bughunting/client.yml"



def usage
  puts \
    "usage: #{$PROGRAM_NAME} [options] [command] [task]\n\n" \
    "    options:\n" \
    "              -q                     non-verbose output\n" \
    "    \n" \
    "    commands: check (default)        verify current solution\n" \
    "              list                   list all tasks\n" \
    "              clean                  restore task original files\n" \
    "              patch                  show patch (changes)\n\n" \
    "              restart                restart local huntserver\n\n" \
    "              log                    show last task log\n\n" \
    "    task name will be autodetected if not supplied\n"
end

def error(message)
  $stderr.puts "%s: %s" % ["ERROR".bold.red, message]
end


if ARGV.first == '-h' || ARGV.first == '--help'
    usage
    exit
end

if ARGV.first == '-q'
    verb = false
    ARGV.shift
else
    verb = true
end

command = ARGV.shift
task = ARGV.shift

command ||= "check"

unless ["check", "list", 'patch', 'clean'].include? command
  error "Invalid command."
  usage
  exit 2
end

user_key = ENV['KEY']

if user_key.nil? || user_key.empty?
  error "ENV KEY missing!"
  exit 3
end

begin
  controller = ClientController.new client_config, user_key, task, verb
  result = controller.send command
  exit result ? 0 : 1
rescue Errno::ECONNREFUSED
  error "Cannot connect to the testing server."
rescue ClientError => e
  error "%s" % e.message
rescue => e
  error "Unexpected error #{e}:\n#{e.message}\n"
  puts e.backtrace
end

exit 2
