$LOAD_PATH.unshift(*Dir[File.expand_path("../../lib", __FILE__), File.expand_path("../../modules", __FILE__)])

raise "win-service executable can only be used as a service in windows environment" unless RUBY_PLATFORM =~ /mingw/

require 'win32/daemon'
require 'logger'
require 'smart_proxy_main'

include Win32

LOG_DIR_PATH = File.expand_path("../../log", __FILE__)
Dir.mkdir(LOG_DIR_PATH) unless Dir.exist?(LOG_DIR_PATH)

def logger
  @logger ||= Logger.new(File.expand_path("win-service.log", LOG_DIR_PATH))
end

begin
  class SmartDaemon < Daemon
    def service_init
      logger.info("Service is initializing")
    end

    def service_main
      logger.info("Service is running")
      # Start the foreman daemon
      Proxy::Launcher.new.launch

      # the daemon is about to exit.
      logger.info("Service is terminating")
    end

    def service_stop
      logger.info("Service is stopping.")
    end    
  end

  SmartDaemon.mainloop
rescue Exception => e
  logger.error("Daemon failure: #{e}  #{e.backtrace.join("\n")}")
  raise
end
