1# -*- coding: us-ascii -*-
2require 'erb'
3require 'optparse'
4require 'fileutils'
5$:.unshift(File.dirname(__FILE__))
6require 'vpath'
7
8vpath = VPath.new
9timestamp = nil
10output = nil
11ifchange = nil
12
13opt = OptionParser.new do |o|
14  o.on('-t', '--timestamp[=PATH]') {|v| timestamp = v || true}
15  o.on('-o', '--output=PATH') {|v| output = v}
16  o.on('-c', '--[no-]if-change') {|v| ifchange = v}
17  vpath.def_options(o)
18  o.order!(ARGV)
19end
20template = ARGV.shift or abort opt.to_s
21erb = ERB.new(File.read(template), nil, '%')
22erb.filename = template
23result = erb.result
24if output
25  if ifchange and (vpath.open(output) {|f| f.read} rescue nil) == result
26    puts "#{output} unchanged"
27  else
28    open(output, "wb") {|f| f.print result}
29    puts "#{output} updated"
30  end
31  if timestamp
32    if timestamp == true
33      dir, base = File.split(output)
34      timestamp = File.join(dir, ".time." + base)
35    end
36    FileUtils.touch(timestamp)
37  end
38else
39  print result
40end
41