#!/usr/bin/env ruby

require 'etc'
require 'yaml'
require 'daemons/daemonize'
require 'stomp_server'
require 'optparse'

$STOMP_SERVER = true

$HTTP_ENABLE = false
if $HTTP_ENABLE
  require 'mongrel'
  require 'stomp_server/protocols/http'
end


EventMachine::run do

  ## Get the configuration and initialize the stomp engine
  config = StompServer::Configurator.new
  stomp = StompServer::Run.new(config.opts)
  stomp.start


  # Might want to uncomment this if you are sending large files
  #EventMachine::add_periodic_timer 10, proc {GC.start}
  
  puts "Client authorization enabled" if config.opts[:auth]
  puts "Debug enabled" if config.opts[:debug]

  ## Start protocol handlers

  puts "Stomp protocol handler starting on #{config.opts[:host]} port #{config.opts[:port]}"
  stomp_proto = StompServer::Protocols::Stomp
  stomp_proto.class_variable_set(:@@auth_required, stomp.auth_required)
  stomp_proto.class_variable_set(:@@queue_manager, stomp.queue_manager)
  stomp_proto.class_variable_set(:@@topic_manager, stomp.topic_manager)
  stomp_proto.class_variable_set(:@@stompauth, stomp.stompauth)
  EventMachine.start_server(config.opts[:host], config.opts[:port], stomp_proto) {|_s|
    # class-level state configured above
  }

  if $HTTP_ENABLE
    puts "Http protocol handler starting on #{config.opts[:host]} port 8080"
    http_proto = StompServer::Protocols::Http
    http_proto.class_variable_set(:@@auth_required, stomp.auth_required)
    http_proto.class_variable_set(:@@queue_manager, stomp.queue_manager)
    http_proto.class_variable_set(:@@topic_manager, stomp.topic_manager)
    http_proto.class_variable_set(:@@stompauth, stomp.stompauth)
    EventMachine.start_server(config.opts[:host], 8080, http_proto) {|_s|
      # class-level state configured above
    }
  end
end
