#!/usr/bin/ruby

require 'webrick'
require 'optparse'
require 'fileutils'

pwd = File.expand_path(File.dirname(__FILE__) + "/..")

OPTIONS = {
  :port        => 3000,
  :ip          => "0.0.0.0",
  :environment => "production",
  :server_root => File.expand_path(File.dirname(__FILE__) + "/../public/"),
  :server_type => WEBrick::SimpleServer,
  :storage     => "#{File.expand_path(FileUtils.pwd)}/storage"
}

ARGV.options do |opts|
  script_name = File.basename($0)
  opts.banner = "Usage: ruby #{script_name} [options]"

  opts.separator ""

  opts.on("-p", "--port=port", Integer,
          "Runs Rails on the specified port.",
          "Default: 3000") { |OPTIONS[:port]| }
  opts.on("-b", "--binding=ip", String,
          "Binds Rails to the specified ip.",
          "Default: 0.0.0.0") { |OPTIONS[:ip]| }
  opts.on("-e", "--environment=name", String,
          "Specifies the environment to run this server under (test/development/production).",
          "Default: development") { |OPTIONS[:environment]| }
  opts.on("-d", "--daemon",
          "Make Rails run as a Daemon (only works if fork is available -- meaning on *nix)."
          ) { OPTIONS[:server_type] = WEBrick::Daemon }
  opts.on('-v', '--verbose', 
          'Enables debug-level logging') { OPTIONS[:verbose] = true }
  
  opts.separator ""

  opts.on("-h", "--help",
          "Show this help message.") { puts opts; exit }

  opts.parse!
end

if OPTIONS[:environment] == 'production'
  storage_path = "#{OPTIONS[:storage]}/#{OPTIONS[:port]}"
else
  storage_path = "#{OPTIONS[:storage]}/#{OPTIONS[:environment]}/#{OPTIONS[:port]}"
end
FileUtils.mkdir_p(storage_path)

ENV["RAILS_ENV"] = OPTIONS[:environment]
$lesserwiki_debug_logging = OPTIONS[:verbose]
require File.dirname(__FILE__) + "/../config/environment"

require 'webrick_server'
require_dependency 'application'
OPTIONS['working_directory'] = File.expand_path(RAILS_ROOT)

puts "=> LesserWiki started on http://#{OPTIONS[:ip]}:#{OPTIONS[:port]}"
puts "=> Ctrl-C to shutdown server; call with --help for options" if OPTIONS[:server_type] == WEBrick::SimpleServer

#ApplicationController.storage = WikiStorage.instance
DispatchServlet.dispatch(OPTIONS)
