#!/usr/bin/env ruby

require 'test/unit'
require 'test/unit/ui/console/testrunner'
require 'test/unit/ui/testrunnerutilities'
require 'test/unit/ui/testrunnermediator'
require 'test/unit/autorunner'
require 'optparse'

$LOAD_PATH.unshift File.dirname(__FILE__) + '/../lib'

require 'rubygems'
require 'spec/test_to_spec/translation_test_runner'
require 'spec/version'

$test2spec_options = {
  :collision => :ask,
  :verbose => false
}

opts = OptionParser.new do |opts|
  opts.banner = "Usage: test2spec [options] (FILE|DIRECTORY|GLOB)+"
  opts.separator ""

  opts.on("-s", "--specdir DIRECTORY", "Directory where specs will be written") do |dir|
    $test2spec_options[:specdir] = dir
  end

  opts.on("-t", "--template FILE", 
    "ERB template that will be used to decorate each translated file.",
    "The template has access to the following variables:",
    "  translation   : the translated source code",
    "  depth         : the directory depth of the file to be written",
    "  relative_path : the relative name of the file to be written"
  ) do |file|
    $test2spec_options[:template] = file
  end

  opts.on("-c", "--chmod MODIFIERS", Integer, "Change file modifiers on written files (POSIX only)") do |mods|
    $test2spec_options[:chmod] = mods
  end

  opts.on("--svn", "Add written files to subversion") do
    $test2spec_options[:svn] = true
  end

  opts.on("-f", "--force", "Forcefully overwrite existing specs") do
    $test2spec_options[:collision] = :force
  end

  opts.on("-q", "--quiet", "Don't print anything to stdout") do
    $test2spec_options[:quiet] = true
  end

  opts.on("--verbose", "Be extra verbose (printing backtraces when classes can't be translated)") do
    $test2spec_options[:verbose] = true
  end

  opts.on("-v", "--version", "Show version") do
    puts "test2spec #{Spec::VERSION::DESCRIPTION}"
    exit
  end

  opts.on("-d", "--dry-run", "Don't write anything - just verify that translation works") do
    $test2spec_options[:dry_run] = true
  end

  opts.on_tail("-h", "--help", "You're looking at it") do
    puts opts
    exit
  end
end

opts.parse! ARGV

if($test2spec_options[:specdir].nil?)
  STDERR.puts "ERROR: --specdir must be specified"
  puts opts
  exit 1
end

if(ARGV.empty?)
  STDERR.puts "ERROR: At least one directory, file or glob must be specified"
  puts opts
  exit 1
end

module Test
  module Unit
    class AutoRunner
      def initialize(standalone)
        @standalone = standalone
        @runner = proc { |r| Spec::TestToSpec::TranslationTestRunner }
        @collector = COLLECTORS[(standalone ? :dir : :objectspace)]
        @filters = []
        @to_run = []
        yield(self) if(block_given?)
      end
    end
  end
end

# If ARGV is a glob, it will actually each over each one of the matching files.
ARGV.each do |arg|
  if File.directory?(arg)
    Dir["#{arg}/**/*.rb"].each do |file| 
      require "#{file}"
    end
  else
    require arg
  end
end
