#!/usr/bin/ruby


require "bughunting/common"
require "bughunting/devel/controller"
require "optparse"

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

command = :check
server_config = "/etc/bughunting/server.yml"
task_dir = nil
verbose = false

parser = OptionParser.new do |opts|
  opts.banner = \
    "usage: #{$PROGRAM_NAME} [command]\n\n" \
    "    commands: check (default)        verify current solution\n" \
    "              setup                  create working directory, run setup operations\n" \
    "              patch                  print patch showing changes in working directory\n" \
    "              clean                  clean working directory, recover from setup cache\n" \
    "              superclean             destroy working directory and setup cache\n" \
    "              verify                 verify the patches\n\n"

  opts.on("-r:", "--task-root", "Set task root directory") do |value| task_dir = value end
  opts.on("-c:", "--server-config", "Set server config file") do |value| server_config = value end
  opts.on("-v", "--verbose", "Verbose mode") do |value| verbose = true end
end

args = parser.order!
if args.length == 1 then
  command = args.shift.to_sym
elsif args.length > 1 then
  error "Invalid parameters."
  parser.display
  exit 1
end

# try to find the task dir
if task_dir.nil?
  task_dir = Dir.getwd
  while task_dir != "/"
    config = File.join task_dir, "task.yml"
    break if File.file? config
    task_dir = File.dirname(task_dir)
  end

  if task_dir == "/"
    error "Task root dir not found, use '-r' option."
    exit 1
  end
end

controller = DevelopmentController.new task_dir, server_config, verbose

if [:check, :setup, :patch, :clean, :superclean, :verify].include? command then
  controller.send command
else
  error "Unknown command '#{command.to_s}'."
  parser.display
  exit 1
end
