#!/usr/bin/ruby

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

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

# METHODS
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

def get_env(k)
  v = ENV[k]
  return false if v.nil? || v.empty?
  v
end

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

command = ARGV.shift
task = ARGV.shift

command ||= "check"

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

# ENV
user_key = get_env 'KEY'

unless user_key
  error "Environment value 'KEY' missing!"
  exit 3
end

no_git = get_env 'NOGIT'

# EXEC
begin
  controller = ClientController.new client_config, user_key, task

  unless no_git
    result = controller.send 'git_check'
    if !result
      error "Git state not ready. You need to commit, push, and/or rebase your changes first."
      puts "\n",
        "Possible remedy:\n",
        "  $ git commit -am 'My descriptive commit message.' && git pull && git push"
      exit 4
    end
  end

  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 unless ENV["HUNT_DEBUG"].nil?

end

exit 5
