#!/usr/bin/env ruby
#
# print help
#
require 'rhc/coverage_helper'

# Require rhc-common for wizard invocation
require 'rhc-common'

def p_usage(exit_code = 255)
    puts <<USAGE

Usage: rhc (<resource> | --help) [<command>] [<args>]
Command line tool for performing operations related to your rhcloud account.

List of resources
  domain             Manage the namespace for the registered rhcloud user.
  app                Manage applications within the rhcloud account.
  sshkey             Manage multiple keys for the registered rhcloud user.
  port-forward       Forward remote ports to the workstation
  server             Display information about the status of the service.
  setup              Run the setup wizard to configure your account.

See 'rhc <resource> --help' for more applicable commands and argumments on a specific resource.
USAGE

exit exit_code
end


def get_args
  ARGV.shift
  args = ""
  ARGV.each do|a|
    if ( a.to_s.strip.length == 0 || a.to_s.strip.match(/\s/) ); a = "'#{a}'" end    
    args += " #{a}"
  end
  args
end

def run_setup_wizard_if_needed
  default_setup_wizard unless ARGV.delete('--noprompt')
end

begin
  case ARGV[0]
  when "domain"
    run_setup_wizard_if_needed
    system("rhc-domain #{get_args} 2>&1")
    retcode = $?.exitstatus
  when "app"
    run_setup_wizard_if_needed
    system("rhc-app #{get_args} 2>&1")
    retcode = $?.exitstatus
  when "sshkey"
    run_setup_wizard_if_needed
    system("rhc-sshkey #{get_args} 2>&1")
    retcode = $?.exitstatus
  when "port-forward"
    run_setup_wizard_if_needed
    system("rhc-port-forward #{get_args} 2>&1")
    retcode = $?.exitstatus
  when "-h", "--help", "help", nil
    p_usage 0
  else
    if ["server", "setup"].include?(ARGV[0])
      run_setup_wizard_if_needed if ARGV[0] != "setup"
      begin
        require 'rhc/cli'
        RHC::CLI.start(ARGV)
        retcode = 0
      rescue SystemExit => e
        retcode = e.status
      end
    else
      puts "Invalid rhc command: #{ARGV[0]}"
      p_usage
    end
  end

  if retcode == nil
    retcode = 1

    # return codes for uncaught signals are 128 + the signal code
    retcode = 128 + $?.termsig if $?.signaled? and !$?.termsig.nil?
  end

  exit retcode
rescue Interrupt
  exit 128 + 2 #INT
end
