#!/usr/bin/env ruby
# -*- ruby -*-

$:.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require "rubygems"
require "optparse"
require "rack"
require "yaml"
require "rots"

server_options = {
  :debugger => false,
  :port => 1123,
  :verbose => true,
  :storage => File.join('.', 'tmp', 'rots'),
  :config => <<-DEFAULT_CONFIG
# Default configuration file
identity: john.doe
sreg:
  nickname: jdoe
  fullname: John Doe
  email: jhon@doe.com
  dob: 1985-09-21
  gender: M

  DEFAULT_CONFIG
}

opts = OptionParser.new do |opts|
  opts.banner = "Usage: rots [options]"
  
  opts.separator ""
  opts.separator "Options:"
  
  opts.on("-p", "--port PORT",
            "use PORT (default: 1123)") do |port|
    server_options[:port] = port
  end
  
  opts.on("-s", "--storage PATH",
            "use PATH as the OpenID Server storage path (default: ./tmp/rots)") do |storage_path|
    server_options[:storage] = storage_path
  end
  
  opts.on("-c", "--config FILE.yaml",
            "server configuration YAML file") do |config_path|
    abort "\x1B[31mConfiguration file #{config_path} not found\x1B[0m" unless File.exists?(config_path)
    server_options[:config] = File.new(config_path)
  end
  
  opts.on("-s", "--silent",
            "If specified, the server will be in silent mode") do 
    server_options[:verbose] = false
  end
  
  opts.on("-d", "--debugger") do
    server_options[:debugger] = true
  end
  
  opts.separator ""
  opts.separator "Common options:"
  
  opts.on_tail("-h", "--help", "Show this help message") do
    puts opts
    exit
  end
  
end

opts.parse!(ARGV)

config = YAML.load(server_options[:config])

require "ruby-debug" if server_options[:debugger]

server = Rack::Builder.new do 
  use Rack::Lint
  if server_options[:verbose]
    use Rack::CommonLogger, STDOUT
    use Rack::ShowExceptions
  end
  map ("/%s" % config['identity']) do
    run Rots::IdentityPageApp.new(config, server_options)
  end
  map "/server" do
    run Rots::ServerApp.new(config, server_options)
  end
end

puts "\x1B[32mRunning OpenID Test server on port 1123\x1B[0m" if server_options[:verbose]
begin 
  Rack::Handler::Mongrel.run server, :Port => server_options[:port]
rescue LoadError
  if server_options[:verbose]
    Rack::Handler::WEBrick.run server, :Port => server_options[:port]
  else
    Rack::Handler::WEBrick.run server, :Port => server_options[:port], :AccessLog => [], :Logger => WEBrick::Log::new("/dev/null", 7)
  end
end
