#!/usr/bin/ruby

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

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

OPTIONS = {

  # Overridable options
  :port        => 2500,
  :ip          => '127.0.0.1',
  :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 Instiki on the specified port.',
          'Default: 2500') { |OPTIONS[:port]| }
  opts.on('-b', '--binding=ip', String,
          'Binds Rails to the specified ip.',
          'Default: 127.0.0.1') { |OPTIONS[:ip]| }
  opts.on('-i', '--index=controller', String,
          'Specifies an index controller that requests for root will go to (instead of congratulations screen).'
          ) { |OPTIONS[:index_controller]| }
  opts.on('-e', '--environment=name', String,
          'Specifies the environment to run this server under (test/development/production).',
          'Default: production') { |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('-s', '--simple', '--simple-server',
          '[deprecated] Forces Instiki not to run as a Daemon if fork is available.',
          'Since version 0.10.0 this option is ignored.'
          ) { puts "Warning: -s (--simple) option is deprecated. See instiki --help for details." }
  opts.on('-t', '--storage=storage', String,
          'Makes Instiki use the specified directory for storage.',
          'Default: ./storage/[port]') { |OPTIONS[:storage]| }
  opts.on('-v', '--verbose', 
          'Enable debug-level logging'
          ) { OPTIONS[:verbose] = true }

  opts.separator ''

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

  opts.parse!
end

ENV['RAILS_ENV'] = OPTIONS[:environment]
require File.expand_path(File.dirname(__FILE__) + '/../config/environment')

if OPTIONS[:verbose]
  ActionController::Base.logger.level = Logger::DEBUG
end

OPTIONS[:index_controller] = 'wiki'
require 'webrick_server'

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

puts "=> Starting Instiki on http://#{OPTIONS[:ip]}:#{OPTIONS[:port]}"
puts "=> Data files are stored in #{storage_path}"

require 'application'
WikiService.storage_path = storage_path
ApplicationController.wiki = WikiService.instance
DispatchServlet.dispatch(OPTIONS)