#! /usr/bin/env ruby

require 'rubygems'
require 'clamp'
require 'highline'
HighLine.color_scheme = HighLine::SampleColorScheme.new

# load i18n to get translations
require 'hammer_cli/i18n'

require 'hammer_cli/options/normalizers'
# create fake command instance to use some global args before we start
class PreParser < Clamp::Command
  option ["-v", "--verbose"], :flag, _("be verbose")
  option ["-d", "--debug"], :flag, _("show debugging output")
  option ["-c", "--config"], "CFG_FILE", _("path to custom config file")
  option ["-u", "--username"], "USERNAME", _("username to access the remote system")
  option ["-p", "--password"], "PASSWORD", _("password to access the remote system")
  option ["-s", "--server"], "SERVER", _("remote system address")
  option ["--interactive"], "INTERACTIVE", _("Explicitly turn interactive mode on/off") do |value|
    bool_normalizer = HammerCLI::Options::Normalizers::Bool.new
    bool_normalizer.format(value)
  end
end

preparser = PreParser.new File.basename($0), {}
begin
  preparser.parse ARGV
rescue
end

# load user's settings
require 'hammer_cli/settings'

CFG_PATH_LEGACY = ['~/.foreman/', '/etc/foreman/', "#{::RbConfig::CONFIG['sysconfdir']}/foreman/"].uniq
HammerCLI::Settings.load_from_paths CFG_PATH_LEGACY
if HammerCLI::Settings.path_history.empty?
  CFG_PATH = ['~/.hammer/', '/etc/hammer/', "#{::RbConfig::CONFIG['sysconfdir']}/hammer/"].uniq
  HammerCLI::Settings.load_from_paths CFG_PATH
else
  warn _("Warning: Legacy config paths detected, move the following files")
  HammerCLI::Settings.path_history.each { |p| warn "    #{p} -> #{p.gsub('hammer.modules.d', 'cli.modules.d').gsub('foreman/', 'hammer/')}"}
end

CFG_PATH_LOCAL = ['./config/']

if preparser.config
  CFG_PATH_LOCAL.unshift preparser.config
end

HammerCLI::Settings.load_from_paths CFG_PATH_LOCAL

# store username and password in settings
HammerCLI::Settings.load({
  :_params => {
    :username => preparser.username,
    :password => preparser.password,
    :host => preparser.server,
    :interactive => preparser.interactive,
    :verbose => preparser.verbose? || preparser.debug?
  }})

if HammerCLI::Settings.get(:mark_translated)
  include HammerCLI::I18n::Debug
end

# setup logging
require 'hammer_cli/logger'
logger = Logging.logger['Init']

if preparser.verbose? || preparser.debug?
  root_logger = Logging.logger.root
  root_logger.appenders = root_logger.appenders << ::Logging.appenders.stderr(:layout => HammerCLI::Logger::COLOR_LAYOUT)
  root_logger.level = 'debug' if preparser.debug?
end

require 'hammer_cli/version'
hammer_version = HammerCLI.version.to_s
logger.info "Initialization of Hammer CLI (#{hammer_version}) has started..."
logger.debug "Running at ruby #{RUBY_VERSION}-p#{RUBY_PATCHLEVEL}"


# log which config was loaded (now when we have logging)
HammerCLI::Settings.path_history.each do |path|
  logger.info "Configuration from the file #{path} has been loaded"
end

# load hammer core
require 'hammer_cli'

# load modules set in config
begin
  HammerCLI::Modules.load_all
rescue => e
  handler = HammerCLI::ExceptionHandler.new(:context => {}, :adapter => :base)
  handler.handle_exception(e)
  exit HammerCLI::EX_SOFTWARE
end

# log information about locale
logger.debug "Using locale '#{HammerCLI::I18n.locale}'"
HammerCLI::I18n.domains.each do |domain|
  logger.debug "'#{domain.type}' files for locale domain '#{domain.domain_name}' loaded from '#{File.expand_path(domain.locale_dir)}'"
end

exit HammerCLI::MainCommand.run || HammerCLI::EX_OK
