#!/usr/bin/env ruby
require 'drb'
require 'logger'
require 'optparse'

require 'pry'

require File.expand_path('../../lib/onapp_cli/options', __FILE__)
require File.expand_path('../../lib/onapp_cli/client/drb_server', __FILE__)
require File.expand_path('../../lib/onapp_cli/client/virtual_machines', __FILE__)
require File.expand_path('../../lib/onapp_cli/client/templates', __FILE__)

include OnappCLI::Options

ALIASES = {
  'stop_vm'               => 'stop_virtual_machine',
  'start_vm'              => 'startup_virtual_machine',
  'start_virtual_machine' => 'startup_virtual_machine',
  'build_vm'              => 'build_virtual_machine'
}

options do |opts|
  opts.banner = "  Usage: onapp command [options]"
  opts.separator ""
  opts.separator "Type: onapp help [command]"
  opts.separator "Commands: server, build_vm, start_vm, stop_vm, templates"
  opts.separator ""
  opts.separator "  \033[1mHelp\033[0m" 
  opts.on_tail("--help", "Show this message") do
  end
end

command = ARGV[0]
second_argument = ARGV[1]
case command
when nil, /^-/
  puts opts.to_s
  exit
when 'help'
  case second_argument
  when nil
    puts opts.to_s
  when 'server'
    opts = OptionParser.new
    opts.banner = "  Usage: onapp server [command]"
    opts.separator ""
    opts.separator "Commands: status, start, stop, restart"
    puts opts.to_s
  when 'templates'
    case ARGV[2]
    when nil
      opts = OptionParser.new
      opts.banner = "  Usage: onapp help templates [command]"
      opts.separator ""
      opts.separator "Commands: list, install, update, remove"
      puts opts.to_s
    when /[a-z]+/
      opts = options_for(ARGV[2])
      unless opts
        puts "Options for command 'templates #{ARGV[2]}' not found"
        exit
      end
      puts opts.to_s
    end
  when /[a-z]+_virtual_machine/, /[a-z]+_vm/
    meth = ALIASES[second_argument] ? ALIASES[second_argument] : second_argument
    opts = options_for(meth)
    puts "Options for command '#{second_argument}' not found" unless opts
    puts opts.to_s    
  end
when 'server'
  unless %w(start stop status restart).include?(second_argument)
    puts "Available arguments: start, stop, restart and status"
  else
    OnappCLI::Client::DRbServer.send(second_argument)
  end
  exit
when 'build_vm', 'build_virtual_machine'
  OnappCLI::Client::VirtualMachines.build_virtual_machine
when 'start_vm', 'startup_virtual_machine'
  OnappCLI::Client::VirtualMachines.startup_virtual_machine
when 'stop_vm', 'stop_virtual_machine'
  OnappCLI::Client::VirtualMachines.stop_virtual_machine
when 'templates'
  unless %w(list install update remove).include?(second_argument)
    puts "Available arguments: list, install, update, remove"
  else
    OnappCLI::Client::Templates.send(second_argument)
  end
else
  puts "[Error] Unknown command '#{command}'"
  puts opts.to_s
  exit
end