#!/usr/bin/env ruby
#
# You may specify the path to the FastCGI crash log (a log of unhandled
# exceptions which forced the FastCGI instance to exit, great for debugging)
# and the number of requests to process before running garbage collection.
#
# By default, the FastCGI crash log is RAILS_ROOT/log/fastcgi.crash.log
# and the GC period is nil (turned off).  A reasonable number of requests
# could range from 10-100 depending on the memory footprint of your app.
#
# Example:
#   # Default log path, normal GC behavior.
#   RailsFCGIHandler.process!
#
#   # Default log path, 50 requests between GC.
#   RailsFCGIHandler.process! nil, 50
#
#   # Custom log path, normal GC behavior.
#   RailsFCGIHandler.process! '/var/log/myapp_fcgi_crash.log'
#
require File.dirname(__FILE__) + "/../config/environment"
require 'fcgi_handler'
class RailsFCGIHandler
  private
  # improved version of frao_handler
  # by Chris Gaskett
  # still might need a kill -9 sometimes if processes hangs
    def pfrao_handler(signal)
      dispatcher_log :info, "asked to terminate immediately"
      number_procs = `/bin/ps ux | /bin/grep -c fcgi$`.to_i
	  # note: to_i produces 0 if conversion to integer is not successful
	  case number_procs
	  when 0
	  	dispatcher_log :info, "pfrao handlerf error, check number_procs query, paths.  Exiting"
		exit
	  when 1
	    dispatcher_log :info, "pfrao handler restarting instead, only one process left"
		restart_handler(signal)
	  else
	    dispatcher_log :info, "pfrao handler agreed to exit, more than one process is running"
		exit
	  end
    end
    alias_method :exit_now_handler, :pfrao_handler
  end
  
RailsFCGIHandler.process! nil, 10
# original  below
#class RailsFCGIHandler
#  private
#    def frao_handler(signal)
#      dispatcher_log :info, "asked to terminate immediately"
#      dispatcher_log :info, "frao handler working its magic!"
#      restart_handler(signal)
#    end
#    alias_method :exit_now_handler, :frao_handler
#  end
#RailsFCGIHandler.process!
