#!/usr/bin/env ruby

require 'ec_sync_client/sync_manager'
require 'ec_sync_client/config'
require 'mixlib/cli'

class ECSyncClient
  class Application
    include Mixlib::CLI

    option :config_file,
      :short => "-c CONFIG",
      :long  => "--config CONFIG",
      :default => '/opt/opscode/ec_sync.rb',
      :description => "The configuration file to use"

    option :log_level,
      :short => "-l LEVEL",
      :long  => "--log_level LEVEL",
      :description => "Set the log level (debug, info, warn, error, fatal)",
      :default => :info,
      :proc => Proc.new { |l| l.to_sym }

    option :socket_path,
      :short => "-s PATH",
      :description => "Path for the SyncManager's control socket"

    option :help,
      :short => "-h",
      :long => "--help",
      :description => "Show this message",
      :on => :tail,
      :boolean => true,
      :show_options => true,
      :exit => 0

    def configure_logging
      stdout_logger = MonoLogger.new(STDOUT)
      Chef::Log.logger = stdout_logger
      Chef::Log.level = ECSyncClient::Config[:log_level]
    end

    def load_config(argv)
      parse_options(argv)
      ECSyncClient::Config.from_file(config[:config_file])
      ECSyncClient::Config.merge!(config)
    rescue Errno::ENOENT
      Chef::Log.error "Could not find configuration file: #{config[:config_file]}"
      exit 1
    end

    def run(argv=ARGV)
      load_config(argv)
      configure_logging
      manager = ECSyncClient::Manager.new(ECSyncClient::Config)
      manager.start()
    end
  end
end

app = ECSyncClient::Application.new
app.run
