#!/usr/bin/env ruby

if RUBY_VERSION < '1.8.7'
  abort "error: XCPretty requires Ruby 1.8.7 or higher."
end

if $0 == __FILE__
  $:.unshift File.expand_path('../../lib', __FILE__)
end
require 'xcpretty'
require 'optparse'

report_options = []
report_classes = []
report_formats = {
  "junit" => XCPretty::JUnit,
  "html"  => XCPretty::HTML
}

printer_opts = {
  :unicode => true,
  :colorize => false,
  :formatter => XCPretty::Simple
}

OptionParser.new do |opts|
  opts.banner = "Usage: xcodebuild [options] | xcpretty"
  opts.on('-t', '--test', 'Use RSpec style output') do
    printer_opts[:formatter] = XCPretty::RSpec
  end
  opts.on('-s', '--simple', 'Use simple output (default)') do
    printer_opts[:formatter] = XCPretty::Simple
  end
  opts.on('-f', '--formatter PATH', 'Use formatter returned from evaluating the specified Ruby file') do |path|
    printer_opts[:formatter] = XCPretty.load_custom_formatter(path)
  end
  opts.on('-c', '--color', 'Use colorized output') do
    printer_opts[:colorize] = true
  end
  opts.on('--no-utf', 'Disable unicode characters in output') do
    printer_opts[:unicode] = false
  end
  opts.on("-r", "--report FORMAT", "Run FORMAT reporter",
                "  Choices: #{report_formats.keys.join(', ')}") do |format|
    report_classes << report_formats[format]
    report_options << {}
  end
  opts.on('-o', '--output PATH', 'Write report output to PATH') do |path|
    unless opts = report_options.last
      XCPretty.exit_with_error('Expected report format to be specified before before output path')
    end
    opts[:path] = path
  end
  opts.on_tail('-h', '--help', 'Show this message') { puts opts; exit }
  opts.on_tail("-v", "--version", "Show version") { puts XCPretty::VERSION; exit }
  opts.parse!

  if STDIN.tty?
    XCPretty.exit_with_error(opts.help)
  end
end

printer = XCPretty::Printer.new(printer_opts)
reporters = report_classes.compact.each_with_index.map {|k,i| k.new(report_options[i])}

ARGF.each_line do |line|
  printer.pretty_print(line)
  reporters.each { |r| r.handle(line) }
end

reporters.each(&:finish)