require 'tofu/tofulet'
require 'drb/drb'

class DRbURIServlet < WEBrick::HTTPServlet::AbstractServlet
  def initialize(config, uri)
    @config = config
    @uri = uri
  end
  
  def do_GET(req, res)
    res['content-type'] = 'text/plain'
    res.body = @uri.to_s
  end
end

class TofuRunner
  include DRbUndumped

  def initialize(monolithic=true)
    @logger = WEBrick::Log::new($stderr, WEBrick::Log::DEBUG)

    @server = WEBrick::HTTPServer.new(:Port => 2000,
				      :AddressFamily => Socket::AF_INET,
				      :BindAddress => ENV['HOSTNAME'],
				      :Logger => @logger)
    if monolithic
      require 'amida_div'
      mount_tofulet('/amida', Tofu::Bartender.new(AmidaTofuSession))
    end
  end

  def start
    trap("INT") { @server.shutdown }
    @server.start
  end
  
  def mount_tofulet(point, bartender)
    @server.mount(point, WEBrick::Tofulet, bartender)
  end

  def mount_drburi(point='/drburi', uri=DRb.uri)
    @server.mount(point, DRbURIServlet, uri)
  end
end

if __FILE__ == $0
  all_in_one = false
  case ARGV.shift
  when '-a', '--all'
    all_in_one = true
  end

  DRb.start_service

  server = TofuRunner.new
  server.mount_drburi
  server.start
end

