#!/usr/bin/env ruby

# == Synopsis
#
# rtouch: recursively touch files.
#
# == Usage
#
# rtouch [OPTIONS] file [files...]
#
# -h, --help
#   show help
#
# -t, --time [[CC]YY]MMDDhhmm[.SS]
#   use the given time instead of the current time
#
# files: the files to create or touch.
# If directories, rtouch will update their time and everything within them.
   
require 'find'
require 'FileUtils'
require 'getoptlong'
require 'rdoc/usage'

def parse_time(tstr)
	if tstr =~ /^(\d\d\d\d|\d\d)?(\d\d)(\d\d)(\d\d)(\d\d)(\.(\d\d))?$/
		if $1
			if $1.length == 2
				year = $1.to_i + ((Time.new.year / 100).floor * 100)
			else
				year = $1
			end
		else
			year = Time.new.year
		end
		secs = $7 ? $7 : 0
		return Time.local(year, $2, $3, $4, $5, secs)
	else
		raise "bad time parameter"
	end
end

opts = GetoptLong.new(
					  [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
					  [ '--time', '-t', GetoptLong::REQUIRED_ARGUMENT ]
					 )

time = Time.new
begin
	opts.each do |opt, arg|
		case opt
		when '--help'
			RDoc::usage 0
		when '--time'
			time = parse_time arg
		end
	end
rescue Exception
	puts $!
	RDoc::usage 1
end

if not ARGV.length > 0
	RDoc::usage 1
end

ARGV.each do |dir|
	if File.exists? dir
		Find.find(dir) do |path|
			File::utime time, time, path
		end
	else
		FileUtils.touch dir
		File::utime time, time, dir
	end
end

