#!/usr/bin/ruby


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

client_config = "/etc/bughunting/client.yml"
command = ARGV.shift 
task = ARGV.shift

def usage
  puts \
    "usage: #{$PROGRAM_NAME} [command] [task]\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" \
    "    task name will be autodetected if not supplied\n"
end

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

command ||= "check"

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

user_key = ENV['KEY']

begin
  controller = ClientController.new client_config, user_key, task
  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, %s" % e.message
  puts e.backtrace unless ENV["HUNT_DEBUG"].nil?
end

exit 2
