#!/usr/bin/env ruby

$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 'smart_proxy'
require 'win32/daemon'
include Win32

begin
  logfile = "../../tmp/proxy.log"
  $stdout.reopen(logfile, "a")
  $stdout.sync = true
  $stderr.reopen($stdout)
  puts "#{Time.now}: Service is starting"

  class Daemon
    def service_init
      puts "#{Time.now}: Service is initializing"
    end

    def service_main(*args)
      puts "#{Time.now}: Service is running"
      Proxy::Launcher.new.launch
      puts "#{Time.now}: Service is terminating"
    end

    def service_stop
      puts "#{Time.now}: Service stopped"
      exit!(true)
    end
  end

  daemon = Daemon.new
  daemon.mainloop
rescue Exception => err
  File.open(logfile, (File::APPEND|File::CREAT|File::WRONLY)){ |f| f.puts " ***Daemon failure #{Time.now} err=#{err}" }
  raise
end
