#!/usr/pkg/bin/ruby34

require 'rubygems'
require 'etc'
require 'yaml'
begin
  require 'daemons/daemonize'
rescue LoadError
  $stderr.puts "daemon gem was not found: you can't use option :daemon"
end
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]}"
  EventMachine.start_server(config.opts[:host], config.opts[:port], StompServer::Protocols::Stomp) {|s| s.instance_eval {
      @@auth_required=stomp.auth_required
      @@queue_manager=stomp.queue_manager
      @@topic_manager=stomp.topic_manager
      @@stompauth = stomp.stompauth
    }
  }

  if $HTTP_ENABLE
    puts "Http protocol handler starting on #{config.opts[:host]} port 8080"
    EventMachine.start_server(config.opts[:host], 8080, StompServer::Protocols::Http) {|s| s.instance_eval {
        @@auth_required=stomp.auth_required
        @@queue_manager=stomp.queue_manager
        @@topic_manager=stomp.topic_manager
        @@stompauth = stomp.stompauth
      }
    }
  end
end
