require 'rubygems'
require 'mongrel'
require 'cgi'
begin
  require 'daemons/daemonize'
  HAVE_DAEMONS=true
rescue
  HAVE_DAEMONS=false
end


class CGIFixed < ::CGI
  public :env_table
  attr_reader :options
  
  def initialize(params, data, out, *args)
    @env_table = params
    @args = *args
    @input = StringIO.new(data)
    @out = out
    @options = {}
    super(*args)
  end
  
  def header(options = "text/html")
    if options.class == Hash
      # passing in a header so need to keep the status around and other options
      @options = options
    end

    super(options)
  end

  def status
    s = @options["Status"] || @options["status"]
    s[0 .. s.index(' ')] || "200"
  end

  def args
    @args
  end
  
  def env_table
    @env_table
  end
  
  def stdinput
    @input
  end
  
  def stdoutput
    @out
  end
end


class RailsHandler < Mongrel::HttpHandler
  def initialize(dir)
    @files = Mongrel::DirHandler.new(dir,false)
    @guard = Mutex.new
  end
  
  def process(request, response)
    # not static, need to talk to rails
    return if response.socket.closed?
    
    if @files.can_serve(request.params["PATH_INFO"])
      @files.process(request,response)
    else
      cgi = CGIFixed.new(request.params, request.body, response.socket)
      begin
        
        @guard.synchronize do
          # Rails is not thread safe so must be run entirely within synchronize 
          Dispatcher.dispatch(cgi, ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS, response.body)
        end
    
        response.status = cgi.status
        response.send_status
        response.send_body
      rescue Object => rails_error
        STDERR.puts "calling Dispatcher.dispatch #{rails_error}"
        STDERR.puts rails_error.backtrace.join("\n")
      end
    end
  end
end


if ARGV.length != 2
  STDERR.puts "usage:  mongrel_rails <host> <port>"
  exit(1)
end

# store this for later since Daemonize insists on going to the / root
cwd = Dir.pwd

if HAVE_DAEMONS
  STDERR.puts "Running Mongrel in the background.  See log/mongrel.log for errors."
  Daemonize.daemonize(log_file=File.join(cwd,"log","mongrel.log"))
else
  STDERR.puts "Unable to daemonize.  Running in foreground.  Use CTRL-C to stop."
end

# and go back
Dir.chdir(cwd) do
  require 'config/environment'
  open(File.join(cwd,"log/mongrel-#{ARGV[1]}.pid"),"w") {|f| f.write(Process.pid) }
  h = Mongrel::HttpServer.new(ARGV[0], ARGV[1])
  h.register("/", RailsHandler.new(File.join(cwd,"public")))
  h.run
  
  h.acceptor.join
end
