APPLICATION = 'sleuth'
RAILS_ROOT  = "/sites/#{APPLICATION}/current"

(9000..9004).each do |port|
  God.watch do |w|
    w.name = "#{APPLICATION}-mongrel-#{port}"
    w.interval = 30.seconds # default      
    w.start   = "#{RUBY_PATH} #{MONGREL_PATH} start   -P #{RAILS_ROOT}/log/mongrel.#{port}.pid -e production -c #{RAILS_ROOT} -p #{port} -d"
    w.stop    = "#{RUBY_PATH} #{MONGREL_PATH} stop    -P #{RAILS_ROOT}/log/mongrel.#{port}.pid"
    w.restart = "#{RUBY_PATH} #{MONGREL_PATH} restart -P #{RAILS_ROOT}/log/mongrel.#{port}.pid"
    w.start_grace   = 10.seconds
    w.restart_grace = 10.seconds
    w.pid_file = File.join(RAILS_ROOT, "log/mongrel.#{port}.pid")
    w.uid = 'web'
    w.gid = 'web'

    w.behavior(:clean_pid_file)

    w.start_if do |start|
      start.condition(:process_running) do |c|
        c.interval  = 5.seconds
        c.running   = false
        c.notify    = 'me'
      end
    end

    w.restart_if do |restart|
      restart.condition(:memory_usage) do |c|
        c.above   = 80.megabytes
        c.times   = [3, 5] # 3 out of 5 intervals
        c.notify  = 'me'
      end

      restart.condition(:cpu_usage) do |c|
        c.above   = 50.percent
        c.times   = 5
        c.notify  = 'me'
      end
    end

    # lifecycle
    w.lifecycle do |on|
      on.condition(:flapping) do |c|
        c.to_state      = [:start, :restart]
        c.times         = 5
        c.within        = 5.minute
        c.transition    = :unmonitored
        c.retry_in      = 10.minutes
        c.retry_times   = 5
        c.retry_within  = 2.hours
        c.notify        = 'me'
      end
    end
  end
end