#!/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby -wKU
# == Synopsis
#
# process_plist: substitute ${VARIABLES} in text files
#
# == Usage
#
# --help:
#    show help

require 'getoptlong'
require 'rdoc/usage'
require 'shellwords'

opts = GetoptLong.new(
  [ '--variables', '-v', GetoptLong::REQUIRED_ARGUMENT ],
  [ '--define',    '-d', GetoptLong::REQUIRED_ARGUMENT ],
  [ '--help',      '-h', GetoptLong::NO_ARGUMENT       ]
)

def parse_variables(path)
  res = { }
  data = File.read(path)
  assignments = data.scan(/^(\w+)\s*(=)[ \t]*(.*)$/)
  assignments.each do |arr|
    key, op, value = *arr
    res[key] = Shellwords.shellwords(value)
  end
  res
end

variables = { }

opts.each do |opt, arg|
  case opt
    when '--help'
      RDoc::usage
    when '--variables'
      variables.merge!(parse_variables(arg))
    when '--define'
      if arg =~ /^(\w+)\s*(=)[ \t]*(.*)$/
        variables[$1] = Shellwords.shellwords($3)
      end
  end
end

while gets
  $_.gsub!(/\$\{(.*?)\}/) do
    if variables.include?($1)
      variables[$1]
    elsif ENV.include?($1)
      ENV[$1]
    else
      abort "*** unknown variable: ‘#$1’"
    end
  end
  print $_
end
