#!/usr/bin/env ruby -ws

$h ||= false
$t ||= false
$d ||= false

require 'rubygems'
require 'hoe'
require 'fileutils'
require 'erb'

if $h || ARGV.empty? || ($t && $d) then
  puts "usage: #{File.basename $0} [-d|-t] project"
  puts "  -t = add project to subdir under 'trunk'"
  puts "  -d = add project to subdir under 'dev'"
  exit
end

project = ARGV.shift

abort "Project #{project} seems to exist" if test ?d, project

# variables for erb:
XIF                       = 'FI' + 'X' # prevents extra hits on my TAG reporter
project, file_name, klass = Hoe.normalize_names project
template_path             = File.expand_path("~/.hoe_template")
source_path               = File.join(File.dirname(File.dirname(__FILE__)),
                                      "template")

unless File.directory? template_path then
  FileUtils.cp_r source_path, template_path, :verbose => true
  paths = (Dir["#{template_path}/**/*"] +
           Dir["#{template_path}/**/.*"]).select { |f| File.file? f }
  FileUtils.chmod 0644, paths, :verbose => true
  FileUtils.chmod 0755, paths.grep(/bin\//), :verbose => true
end

FileUtils.cp_r template_path, project, :verbose => true

Dir.chdir project do
  dirs = Dir["**/*"].select { |f| File.directory? f }.sort
  dirs.grep(/file_name/).each do |file|
    FileUtils.mv file, file.gsub(/file_name/, file_name), :verbose => true
  end

  paths = (Dir["**/*"] + Dir["**/.*"]).select { |f| File.file? f }.sort
  paths.each do |path|
    file = File.read path

    warn "erb: #{path}"

    File.open path, "w" do |f|
      f.puts ERB.new(file).result(binding)
    end
  end

  paths.grep(/file_name|\.erb$/).each do |file|
    new_file = file.sub(/file_name/, file_name).sub(/\.erb$/, '')
    FileUtils.mv file, new_file, :verbose => true
  end
end

if $d || $t then
  temp_dir = "#{project}.#{$$}"
  FileUtils.mv project, temp_dir, :verbose => true
  FileUtils.mkdir project, :verbose => true
  FileUtils.mv temp_dir, "#{project}/#{$d ? 'dev' : 'trunk'}", :verbose => true
end

puts
puts "... done, now go fix all occurrences of '#{XIF}':"
if Hoe::WINDOZE then
  puts `findstr /N /S /C:#{XIF} #{project}\\*`
else
  puts `find #{project} -type f | xargs grep -n #{XIF}`.gsub(/\A|\n/, "\n  ")
end
