#!/usr/local/bin/ruby

require 'webrick'
require 'optparse'

fork_available = true
begin
  exit unless fork
rescue NotImplementedError
  fork_available = false
end

OPTIONS = {
  :port        => 3000,
  :ip          => "127.0.0.1",
  :environment => "development",
  :server_root => File.expand_path(File.dirname(__FILE__) + "/public/"),
  :server_type => fork_available ? WEBrick::Daemon : WEBrick::SimpleServer,
}

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: 127.0.0.1") { |OPTIONS[:ip]| }
  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.separator ""

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

  opts.parse!
end

# Hack it up for the gem
unless File.exist? "#{ENV['HOME']}/.elitejournal"
  require 'rubygems'
  require 'sqlite'
  puts 'Running Elite Journal for the first time ...'

  database_yml =<<DBYML
development:
  adapter: sqlite
  dbfile: #{ENV['HOME']}/.elitejournal/elitejournal.db

production:
  adapter: sqlite
  dbfile: #{ENV['HOME']}/.elitejournal/elitejournal.db

test:
  adapter: sqlite
  dbfile: #{ENV['HOME']}/.elitejournal/elitejournal.db

geminstall:
  adapter: sqlite
  dbfile: #{ENV['HOME']}/.elitejournal/elitejournal.db
DBYML

  puts 'Creating environment ...'
  Dir.mkdir "#{ENV['HOME']}/.elitejournal"
  File.open("#{ENV['HOME']}/.elitejournal/database.yml", 'w') do |f|
    f.write(database_yml)
  end

  db = SQLite::Database.new("#{ENV['HOME']}/.elitejournal/elitejournal.db", 0)
  puts "Creating sqlite database ..."
  dbdef = File.open(File.dirname(__FILE__) + "/db/db-sqlite.sql", "r").readlines.join()
  defusr = File.open(File.dirname(__FILE__) + "/db/default_user.sql", "r").readlines.join()
  db.execute_batch dbdef
  db.execute_batch defusr
  db.close
  puts 'Done.'
end



ENV["RAILS_ENV"] = 'geminstall'

require File.dirname(__FILE__) + "/config/environment"
require 'webrick_server'

# This is so digusting I can hardly look at it.  But it works.  Long live Ruby!
class DispatchServlet
  alias :orig_do_GET :do_GET

  def do_GET(req, res)
    if /\/(\d{4})\/(\d{1,2})\/(\d{1,2})\/?/ =~ req.request_uri.path
      req.request_uri.path = "/dispatch.rb"
      req.request_uri.query = "controller=journal&action=range&year=#{$1}&month=#{$2}&day=#{$3}"
      handle_dispatch(req, res)
      return
    end
    if /\/(\d{4})\/(\d{1,2})\/?/ =~ req.request_uri.path
      req.request_uri.path = "/dispatch.rb"
      req.request_uri.query = "controller=journal&action=range&year=#{$1}&month=#{$2}"
      handle_dispatch(req, res)
      return
    end
    if /\/(\d{4})\/?/ =~ req.request_uri.path
      req.request_uri.path = "/dispatch.rb"
      req.request_uri.query = "controller=journal&action=range&year=#{$1}"
      handle_dispatch(req, res)
      return
    end
    if /\/view\/(\d+)\/?/ =~ req.request_uri.path
      req.request_uri.path = "/dispatch.rb"
      req.request_uri.query = "controller=journal&action=view&id=#{$1}"
      handle_dispatch(req, res)
      return
    end

    orig_do_GET(req, res)
  end
end




OPTIONS[:index_controller] = "journal"

puts "=> Elite Journal started on http://#{OPTIONS[:ip]}:#{OPTIONS[:port]}"
DispatchServlet.dispatch(OPTIONS)
