#!/usr/bin/env ruby
#
#  Created on 2008-6-12.
#  Copyright (c) 2008. All rights reserved.

# NOTE: Adding gem lib dir to includes path
# This probably isn't the right way to do this, but until I know how
# this works.
$:.unshift "#{File.dirname(__FILE__)}/../lib/"

begin
  require 'rubygems'
rescue LoadError
  # no rubygems to load, so we fail silently
end

require 'optparse'
require 'java_properties'
require 'yaml'

OPTIONS = {
  :stdin     => false
}
MANDATORY_OPTIONS = %w(  )

parser = OptionParser.new do |opts|
  opts.banner = <<BANNER
Converts a Java properties file to YAML.

Usage: #{File.basename($0)} [options] [INPUT] [OUTPUT]

Options are:
BANNER
  opts.separator ""
  opts.on("-s", "--stdin",
          "Read input from standard input instead of an input file") { |OPTIONS[:path]| }
  opts.on("-h", "--help",
          "Show this help message.") { puts opts; exit }
  opts.parse!(ARGV)

  if MANDATORY_OPTIONS && MANDATORY_OPTIONS.find { |option| OPTIONS[option.to_sym].nil? }
    puts opts; exit
  end
  if ARGV.empty? && !OPTIONS[:stdin] 
    puts opts; exit
  end
end

infile = $stdin
outfile = $stdout

stdin = OPTIONS[:stdin] ? $stdin : false

begin
  infilepath  = ARGV.shift unless(ARGV.empty? || stdin)
  infile  = File.open(infilepath,'r') if infilepath
  outfilepath = ARGV.shift unless(ARGV.empty?)
  outfile = File.open(outfilepath,'w') if outfilepath
rescue
  $stderr.puts "Error opening input properties file '#{infilepath}' for reading." unless infile.is_a? File
  $stderr.puts "Error opening output YAML file '#{outfilepath}' for writing." if  infile.is_a? File
  exit 1
end

props = {}
JavaProperties::Parser.parse( infile.read ).each do |key,value|
  # Convert all of the keys in the properties file to strings
  # so that they don't output as symbols in the to_yaml results
  props[key.to_s] = value
end
outfile.puts props.to_yaml
