#!/usr/bin/env ruby

require 'optparse'
defaults = { :foreman_path => File.expand_path("../..", __FILE__),
             :environment => "production"}
options = defaults.dup
warn 'foreman-config script is deprecated. Please consider using `foreman-rake config` instead'

option_parser = OptionParser.new do |opt|
  opt.banner = <<BANNER
Wrapper around foreman-rake config task

It's kept here for backward compatibility purposes.
The preffered way should be `foreman-rake config`. See
`foreman-rake config -- --help` for details.
BANNER
  opt.on("-p",
         "--path PATH",
         "Path with Foreman source code (default #{defaults[:foreman_path]})") do |val|
    options[:foreman_path] = val
  end
  opt.on("-e",
         "--env ENV",
         "Runtime environment (default #{defaults[:environment]})") do |val|
    options[:environment] = val
  end
  # pass the -v and -h options to the rake task
  opt.on('-v') { raise OptionParser::InvalidOption }
  opt.on('-h') { raise OptionParser::InvalidOption }
end

rake_args = []
argv = ARGV.dup

begin
  option_parser.parse! argv
rescue OptionParser::InvalidOption => e
  # don't fail on unknown attributes, rather pass it to the rake task
  e.recover argv
  rake_args << argv.shift
  rake_args << argv.shift if !argv.empty? and argv.first !~ /^-/
  retry
end

Dir.chdir(options[:foreman_path]) do
  ENV['RAILS_ENV'] = options[:environment]
  exec('rake', '--', 'config', *rake_args)
end
