# we must require rubygems because LocalService account don't have RUBYOPT= defined
require 'rubygems'
require "win32/service"

SERVICE_NAME = "MongrelHttp"
SERVICE_DISPLAYNAME = "Mongrel Basic HTTP Service"
SERVICE_ROOT = File.expand_path(File.dirname(__FILE__))
SERVICE_SCRIPT = File.join(SERVICE_ROOT, __FILE__)

if ARGV[0] == "install"
  require 'rbconfig'
  
  argv = []
  argv << '"' + Config::CONFIG['bindir'] + '/rubyw.exe"'
  argv << '"' + SERVICE_SCRIPT + '"'
  
  svc = Win32::Service.new
  begin
		svc.create_service{ |s|
			s.service_name     = SERVICE_NAME
			s.display_name     = SERVICE_DISPLAYNAME
			s.binary_path_name = argv.join(' ')
			s.dependencies     = []
		}
		puts "#{SERVICE_DISPLAYNAME} service installed"
	rescue Win32::ServiceError => err
		puts "There was a problem installing the service:"
		puts err
	end
  svc.close

elsif ARGV[0] == "start"
	begin
		Win32::Service.start(SERVICE_NAME)
		started = false
		while started == false
			s = Win32::Service.status(SERVICE_NAME)
			started = true if s.current_state == "running"
			break if started == true
			puts "One moment, " + s.current_state
			sleep 1
		end
		puts "#{SERVICE_DISPLAYNAME} service started"
	rescue Win32::ServiceError => err
		puts "There was a problem installing the service:"
		puts err
	end
	
elsif ARGV[0] == "stop"
	begin
		Win32::Service.stop(SERVICE_NAME)
		stopped = false
		while stopped == false
			s = Win32::Service.status(SERVICE_NAME)
			stopped = true if s.current_state == "stopped"
		break if stopped == true
			puts "One moment, " + s.current_state
			sleep 1
		end
		puts "#{SERVICE_DISPLAYNAME} service stopped"
	rescue Win32::ServiceError => err
		puts "There was a problem installing the service:"
		puts err
	end

elsif ARGV[0] == "remove"
  begin
    Win32::Service.stop(SERVICE_NAME)
  rescue
  end
  begin
    Win32::Service.delete(SERVICE_NAME)
  rescue
  end
  puts "#{SERVICE_DISPLAYNAME} service removed."
else

  # This was added to avoid users running the service script form plain command line
  # (LocalService accound don't have HOMEDRIVE defined.)
  if ENV["HOMEDRIVE"]!=nil
    puts "No option provided.  You must provide an option.  Exiting..."
    exit
  end

  require 'mongrel'
  require 'yaml'
  require 'zlib'
  
  class SimpleHandler < Mongrel::HttpHandler
      def process(request, response)
        response.start do |head,out|
          head["Content-Type"] = "text/html"
          results = "<html><body>Your request:<br /><pre>#{request.params.to_yaml}</pre><a href=\"/files\">View the files.</a></body></html>"
          if request.params["HTTP_ACCEPT_ENCODING"] == "gzip,deflate"
            head["Content-Encoding"] = "deflate"
            # send it back deflated
            out << Zlib::Deflate.deflate(results)
          else
            # no gzip supported, send it back normal
            out << results
          end
        end
      end
  end

	def log(message)
		if !$log_file
			$log_file = File.open(File.join(SERVICE_ROOT, 'service.log'), 'a+')
		end

		$log_file.puts(Time.now.strftime("%Y-%m-%d %H:%M:%S") + ' - ' + message)
		$log_file.flush
	end

  class HttpDaemon < Win32::Daemon
    def service_init
      log "** #{SERVICE_DISPLAYNAME} starting..."
      
      @config = Mongrel::Configurator.new :host => "0.0.0.0" do
        listener :port => 3000 do
          uri "/", :handler => SimpleHandler.new
          uri "/files", :handler => Mongrel::DirHandler.new(SERVICE_ROOT)
        end
      end
			
      log "** Done initialization."
    end

		# I commented this because doing file handling or actually stopping the listeners 
		# here brake the service.
		# My guess is because the ruby interperter was called from a Thread different 
		# than the one where was initialized (but, as usual, could be wrong).
		# I think this need to be reported to win32utils guys.
		#def service_stop
		#	log "Stop Signal received."
		#end
			
    def service_main
			log "Entering Service Main"
			@config.run
			
			while state == RUNNING
				sleep 1
			end
			
			@config.stop
			log "Leaving Service Main"
    end
  end 

  svc = HttpDaemon.new
  svc.mainloop
  
end














