#!/usr/bin/env ruby

# heavily inspired by https://gist.github.com/765432 :)

dry_run = ARGV.delete('--dry-run')
force = ARGV.delete('--force')

input, output, garlic_version = ARGV.length == 1 ?
  [ARGV, ARGV.first.sub(/\.js$/, '.min.js'), 'x.x.x'] :
  [ARGV[0..-3], ARGV.at(-2), ARGV.last]

if (missing = input.select { |path| !File.exists?(path) }).any?
  puts "Some input files do not exist:\n  #{missing.join("  \n")}"
  exit 1
end

if File.exists?(output) && !force
  puts "Output file #{output} already exists, use the --force to overwrite"
  exit 1
end

if dry_run
  puts "#{input.inspect} => #{output}"
else
  require 'rubygems'

  begin
    require 'closure-compiler'
  rescue LoadError
    puts "Error loading Closure Compiler gem:\n  gem install closure-compiler"
    exit 1
  end

  File.open(output, 'w') do |f|
    f.write "/* Parsley %s build version %s http://parsleyjs.org */\n" %
                    [output, garlic_version]
    f.write Closure::Compiler.new.compile_files(input)
  end
end
