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 'dip_div'
      mount_tofulet('/div', Tofu::Bartender.new(DipTofuSession))
    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

  if all_in_one
    require 'dip/dip'
    require 'dip_div'

    puts 'phrase: '
    phrase = gets.chomp
    daemon = DIP::Daemon.new(phrase)
    DipApp.front = daemon.front
  end

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

