#!/usr/bin/env ruby
 
require File.dirname(__FILE__) + '/../config/boot'

require 'webrick'
require 'webrick/https'

OPTIONS = {
  :port => 3001,
  :ip => "0.0.0.0",
  :environment => (ENV['RAILS_ENV'] || "development").dup,
  :server_root => File.expand_path(RAILS_ROOT + "/public/"),
  :pkey => OpenSSL::PKey::RSA.new(File.open(RAILS_ROOT + "/config/certs/server.key").read),
  :cert => OpenSSL::X509::Certificate.new(File.open(RAILS_ROOT + "/config/certs/server.crt").read),
  :server_type => WEBrick::SimpleServer,
  :charset => "UTF-8",
  :mime_types => WEBrick::HTTPUtils::DefaultMimeTypes,
  :debugger => false,
  :detach => false
}

require 'optparse'

ARGV.clone.options do |opts|
  opts.on("-p", "--port=port", Integer,
    "Runs Rails on the specified port.", "Default: 3001") { |v| OPTIONS[:port] = v }
  opts.on("-b", "--binding=ip", String,
    "Binds Rails to the specified ip.", "Default: 0.0.0.0") { |v| OPTIONS[:ip] = v }
  opts.on("-d", "--daemon", "Make server run as a Daemon.") { OPTIONS[:detach] = true }
  opts.on("-e", "--environment=name", String,
    "Specifies the environment to run this server under (test/development/production).",
    "Default: development") { |v| OPTIONS[:environment] = v }
  opts.separator ""
  opts.on("-h", "--help", "Show this help message.") { puts opts; exit }

  opts.parse!
end
 
ENV["RAILS_ENV"] = OPTIONS[:environment]
RAILS_ENV.replace(OPTIONS[:environment]) if defined?(RAILS_ENV)
 
puts "=> Booting WEBrick..."

require RAILS_ROOT + "/config/environment"
require 'webrick_server'
OPTIONS['working_directory'] = File.expand_path(RAILS_ROOT)
 
class SSLDispatchServlet < DispatchServlet
  def self.dispatch(options)
    WEBrick::Daemon.start if options[:detach]
  
    Socket.do_not_reverse_lookup = true
    server = WEBrick::HTTPServer.new(
      :Port => options[:port].to_i,
      :ServerType => options[:server_type],
      :BindAddress => options[:ip],
      :SSLEnable => true,
      :SSLVerifyClient => OpenSSL::SSL::VERIFY_NONE,
      :SSLCertificate => options[:cert],
      :SSLPrivateKey => options[:pkey],
      :SSLCertName => [ [ "CN", WEBrick::Utils::getservername ] ]
    )
 
    server.mount('/', DispatchServlet, options)
    trap("INT") { server.shutdown; exit! }
    trap("TERM") { server.shutdown; exit! }
 
    server.start
  end
end
 
puts "=> Rails application starting on https://#{OPTIONS[:ip]}:#{OPTIONS[:port]}"
puts "=> Ctrl-C to shutdown server"
 
SSLDispatchServlet.dispatch(OPTIONS)
