#!/usr/bin/env jruby
require 'rubygems'
require 'optparse'
require 'stringio'
require 'rspec'
require 'rbconfig'
require 'operawatir'
require 'operawatir/helper'

@options = {
  :manual        => false,
  :ng            => false,
  :color_enabled => true,
  :check_syntax  => false,
  :output_stream => IO.new(1, 'w'),
  :format        => 'progress',
  :no_quit       => false,
  :opera_idle    => true
}

# TODO
#   Should steal https://github.com/rspec/rspec-core/blob/master/lib/rspec/core/option_parser.rb

begin
  OptionParser.new do |opts|
    opts.banner = <<EOS
Usage: operawatir [-m|--manual] [-l|--launcher=BINARY] [-b|--binary=BINARY]
       [-a|--args=ARGUMENTS] [-q|--no-quit] [--no-opera-idle] [--no-color]
       [-f|--format=FORMAT] [-o|--out=FILE] [-h|--help] [-v|--version] FILES
EOS

    opts.separator ""
    opts.separator "Specific options:"

    opts.on('-m', '--manual', 'Wait for a manual connection from opera:debug') do |c|
      @options[:manual] = c
    end

    opts.on('-l', '--launcher=BINARY', 'Path to launcher binary, will use environmental ',
            'variable OPERA_LAUNCHER if not specified') do |c|
      @options[:launcher] = c
    end

    opts.on('-b', '--binary=BINARY', 'Browser to run the test with, will use guess the ',
            'path or use environmental variable OPERA_PATH if ',
            'not specified') do |e|
      @options[:path] = e
    end

    opts.on('-a', '--args=ARGUMENTS', 'Arguments passed to the binary, will override  ',
            'environmental variable OPERA_ARGS') do |a|
      @options[:args] = a
    end

    opts.on('-q', '--no-quit', 'Disable quitting of Opera at the end of a test run') do |c|
      @options[:no_quit] = true
    end

    opts.on('--no-opera-idle', 'Disable OperaIdle') do |c|
      @options[:opera_idle] = false
    end

    opts.on('--no-color', 'Disable colorized output') do |c|
      @options[:color_enabled] = false
    end

    opts.on('-o', '--out=FILE', 'Send output to a file instead of STDOUT') do |o|
      @options[:output_stream] = File.open(o, 'w') or
        abort "operawatir: Unable to write to file `#{o}'"
    end

    opts.on('-f', '--format=FORMAT',
            'Specify RSpec output formatter (documentation, ',
            'html, progress (default), textmate)') do |formatter|
      @options[:formatter] = formatter
    end

    opts.separator ''
    opts.separator 'Common options:'

    opts.on_tail('-h', '--help', 'Show this message') do
      abort opts
    end

    opts.on_tail('-v', '--version', 'Show version') do
      abort "OperaWatir version #{OperaWatir.version}"
    end
  end.parse!(ARGV)
rescue OptionParser::InvalidOption => e
  abort "operawatir: Unknown option `#{e.to_s.sub(/invalid option:\s+/, '')}'"
end

if ARGV.empty?
  abort 'operawatir: You need to specify at least one test file to run'
else
  @options[:files_to_run] = ARGV
end

OperaWatir::Helper.run! @options