#!/usr/bin/env ruby

if ENV['OCTOCATALOG_DIFF_DEVELOPER_PATH']
  # Mostly used for internal testing, to allow pointing of a "real" octocatalog-diff install
  # at code being developed live.
  rel = File.expand_path(ENV['OCTOCATALOG_DIFF_DEVELOPER_PATH'], File.dirname(__FILE__))
  abs = File.expand_path(ENV['OCTOCATALOG_DIFF_DEVELOPER_PATH'])
  if File.directory?(abs) && File.file?(File.join(abs, 'lib', 'octocatalog-diff.rb'))
    require File.join(abs, 'lib', 'octocatalog-diff')
  elsif File.directory?(rel) && File.file?(File.join(rel, 'lib', 'octocatalog-diff.rb'))
    require File.join(rel, 'lib', 'octocatalog-diff')
  else
    raise Errno::ENOENT, "Unable to resolve #{ENV['OCTOCATALOG_DIFF_DEVELOPER_PATH']} (tried #{abs} then #{rel})"
  end
elsif File.file?(File.expand_path('../lib/octocatalog-diff.rb', File.dirname(__FILE__)))
  require_relative '../lib/octocatalog-diff'
else
  require 'octocatalog-diff'
end

config_test = ARGV.include?('--config-test')

paths = [
  ENV['OCTOCATALOG_DIFF_CONFIG_FILE'],
  File.join(Dir.pwd, '.octocatalog-diff.cfg.rb'),
  File.join(ENV['HOME'], '.octocatalog-diff.cfg.rb'),
  '/opt/puppetlabs/octocatalog-diff/octocatalog-diff.cfg.rb',
  '/usr/local/etc/octocatalog-diff.cfg.rb',
  '/etc/octocatalog-diff.cfg.rb'
]

cfgfile = nil

paths.each do |path|
  next if path.nil?
  puts "Looking for config in: #{path}" if config_test
  next unless File.file?(path)
  begin
    cfgfile = path
    puts "Loading config: #{path}" if config_test
    require path
  rescue => exc
    STDERR.puts "#{exc.class} error with #{path}: #{exc.message}\n#{exc.backtrace}"
    exit 1
  end
  break
end

options = {}

if cfgfile
  begin
    options = OctocatalogDiff::Config.config
  rescue => exc
    STDERR.puts "#{exc.class} error with #{cfgfile}: #{exc.message}\n#{exc.backtrace}"
    exit 1
  end
  unless options.is_a?(Hash)
    STDERR.puts "Configuration must be Hash not #{options.class}!"
    exit 1
  end
  if config_test
    options.each do |key, val|
      puts ":#{key} => (#{val.class}) #{val.inspect}"
    end
    exit 0
  end
elsif config_test
  STDERR.puts 'No configuration files found'
  exit 1
end

argv = ARGV.dup
exit_code = OctocatalogDiff::CatalogDiff::Cli.cli(argv, Logger.new(STDERR), options)
exit(exit_code)
