#!/usr/bin/env ruby
#
# Control script for Mongrel by Winson.

SCRIPT_VERSION = '0.6'

APP_DIR = '/home/winson/projects'
APPS = {
'mephisto' => 3100,
'money' => 3200,
'devalot' => 3400,
'radiant' => 3500
}

def is_cluster?(app)
File.exists?(File.join(APP_DIR, app, "config", "mongrel_cluster.yml"))
end

def is_started?(app)
begin
Dir.open(File.join(APP_DIR, app, "log")).each { |filename| return true if filename =~ /mongrel.*pid/ }
rescue
puts "#{app.upcase} is messed up."
end
end

def ask_status(app)
if is_started?(app) == true
puts "Status Running: #{app.upcase}"
else
puts "Status Shutdown: #{app.upcase}"
end
end

def do_start(app, port=nil)
if is_started?(app) == true
ask_status app
else
path = File.join(APP_DIR, app)
puts "Running #{app.upcase} on port #{port}..."
exec "mongrel_rails start -d -p #{port} -e production -c #{path} -P log/mongrel.pid"
end
end

def do_stop(app)
if is_started?(app) == true
path = File.join(APP_DIR, app)
puts "Shutdown #{app.upcase}..."
exec "mongrel_rails stop -c #{path} -P log/mongrel.pid"
else
ask_status app
end
end

def do_restart(app, port=nil)
if is_started?(app) == true
path = File.join(APP_DIR, app)
puts "Shutdown #{app.upcase}..."
exec "mongrel_rails stop -c #{path} -P log/mongrel.pid"
puts "Running #{app.upcase} on port #{port}..."
exec "mongrel_rails start -d -p #{port} -e production -c #{path} -P log/mongrel.pid"
else
ask_status app
end
end

def list
puts "Directory: #{APP_DIR}"
APPS.each {|app, port| puts "Port #{port}: #{app.upcase}"}
end

def start
ARGV[1] ? do_start(ARGV[1]) : APPS.each {|app, port| do_start(app, port)}
end

def status
ARGV[1] ? ask_status(ARGV[1]) : APPS.each {|app, port| ask_status(app)}
end

def stop
ARGV[1] ? do_stop(ARGV[1]) : APPS.each {|app, port| do_stop(app)}
end

def restart
ARGV[1] ? do_restart(ARGV[1]) : APPS.each {|app, port| do_restart(app, port)}
end

def version
puts "Version: #{SCRIPT_VERSION}."
end

def method_missing(method_id)
puts "Usage: mong.rb [help|list|start|status|stop|restart|version] [appname]"
exit
end

send ARGV[0] || :help