#!/System/Library/Frameworks/Ruby.framework/Versions/Current/usr/bin/ruby
# == Synopsis
#
# process_plist: substitute ${VARIABLES} in text files
#
# == Usage
#
# --help:
#    show help
$KCODE = 'U' if RUBY_VERSION < "1.9"

require 'optparse'
require 'shellwords'

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 = { }
OptionParser.new do |opts|
  opts.banner = "Usage: gen_build [options]"
  opts.separator "Synopsis:"
  opts.separator "gen_build: substitute ${VARIABLES} in text files"
  opts.separator "Options:"
  opts.on("-h","--help", "show help.") do |v|
    puts opts
    exit
  end

  opts.on("-v","--variables FILE", "the «file» to write build info into.") do |arg|
    variables.merge!(parse_variables(arg))
  end

  opts.on("-d", "--define NAME=VALUE", "define a variable that ends up in build.ninja") do |arg|
    if arg =~ /^(\w+)\s*(=)[ \t]*(.*)$/
      variables[$1] = Shellwords.shellwords($3)
    end
  end
end.parse!

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