after "servers:setup", "monit:setup"

set :monit_daemon_interval, "120"
set :monit_alert_email, "email@address"

namespace :monit do
desc "Setup monit daemon monitoring"
task :setup do

monit_configuration = <<-EOF
# This monit configuration was generated dynamically
set daemon #{monit_daemon_interval}
set logfile syslog facility log_daemon
set mailserver localhost
set alert #{monit_alert_email}

check system #{domain}
if loadavg (1min) > 4 then alert
if loadavg (5min) > 2 then alert
# if memory usage > 75% then alert
# if cpu usage (user) > 70% then alert
# if cpu usage (system) > 30% then alert
# if cpu usage (wait) > 20% then alert

EOF
put monit_configuration, "#{shared_path}/main.conf"
sudo "cp #{shared_path}/main.conf /etc/monit.d/"
sudo "rm -f #{shared_path}/main.conf"

monit_mongrel_configuration = <<-EOF
# This monit configuration was generated dynamically
#
EOF

(0..mongrel_servers-1).each do |server|
monit_mongrel_configuration +=<<-EOF
check process mongrel-#{mongrel_port + server} with pidfile /var/run/mongrel_cluster/#{application}.#{mongrel_port + server}.pid
group mongrel
start program = "/usr/bin/mongrel_rails cluster::start -C /etc/mongrel_cluster/#{application}.conf --only #{mongrel_port + server} --clean"
stop program = "/usr/bin/mongrel_rails cluster::stop -C /etc/mongrel_cluster/#{application}.conf --only #{mongrel_port + server} --force --clean"
if totalmem > 100.0 MB for 5 cycles then restart
# if failed port #{mongrel_port + server} protocol http with timeout 45 seconds then restart

EOF
end

put monit_mongrel_configuration, "#{shared_path}/#{application}.conf"
sudo "cp #{shared_path}/#{application}.conf /etc/monit.d/"
sudo "rm -f #{shared_path}/#{application}.conf"

# ** merb specific **
monit_merb_configuration = <<-EOF
# This monit configuration was generated dynamically
#
EOF

(0..merb_proxy_servers-1).each do |server|
monit_merb_configuration +=<<-EOF
check process merb-#{merb_proxy_port + server} with pidfile /var/www/apps/scout_merb/shared/log/merb.#{merb_proxy_port + server}.pid
group merb
start program = "/usr/bin/merb --merb-root /var/www/apps/scout_merb/current --daemonize --port #{merb_proxy_port + server} --environment production --log /var/www/apps/scout_merb/current/log/merb.log"
as uid deploy and gid deploy
stop program = "/usr/bin/merb --merb-root /var/www/apps/scout_merb/current --graceful #{merb_proxy_port + server}"
as uid deploy and gid deploy
if totalmem > 100.0 MB for 5 cycles then restart
# if failed port #{merb_proxy_port + server} protocol http with timeout 45 seconds then restart

EOF
end

put monit_merb_configuration, "#{shared_path}/scout_merb.conf"
sudo "cp #{shared_path}/scout_merb.conf /etc/monit.d/"
sudo "rm -f #{shared_path}/scout_merb.conf"

end

desc "Restart monit daemon monitoring"
task :restart do
sudo "/etc/init.d/monit restart"
end
end