#!/usr/bin/env ruby
require 'rubygems'
require 'trollop'
require 'sup'
require 'sup/server'
require 'pp'
require 'yaml'
include Redwood

global_opts = Trollop::options do
  #version = "sup-cmd (sup #{Redwood::VERSION})"
  banner <<EOS
Interact with a Sup index.

Usage:
  sup-server [options]
EOS

  opt :host, "address to listen on", :type => :string, :default => 'localhost', :short => 'o'
  opt :port, "port to listen on", :type => :int, :default => 4300
  opt :verbose
end

Redwood.start
Index.init
Index.lock_interactively or exit
begin
  if(s = Redwood::SourceManager.source_for SentManager.source_uri)
    SentManager.source = s
  else
    Redwood::SourceManager.add_source SentManager.default_source
  end

  Index.load

  EM.run do
    EM.start_server global_opts[:host], global_opts[:port],
                    Redwood::Server, Index.instance
    EM.next_tick { puts "ready" }
  end

ensure
  Index.unlock
end
