#!/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 start(app, port)
if is_started?(app) == true
puts "#{app.upcase} is running."
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 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
puts "#{app.upcase} is shutdown."
end
end

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

if ['stop', 'restart'].include? ARGV.first
if ARGV[1]
stop(ARGV[1])
else
APPS.each {|app, port| stop(app)}
end
end

if ['start', 'restart'].include? ARGV.first
if ARGV[1]
start(ARGV[1], APPS[ARGV[1]])
else
APPS.each {|app, port| start(app, port)}
end
end

if ARGV.first == "list"
puts "Directory: #{APP_DIR}"
APPS.each {|app, port| puts "Port #{port}: #{app.upcase}"}
end

if ARGV.first == "status"
APPS.each {|app, port| status(app)}
end

if ARGV.first == "version"
puts "Version: #{SCRIPT_VERSION}."
end

unless ['list', 'status', 'start', 'stop', 'restart'].include? ARGV.first
puts "Usage: mong [list|status|start|stop|restart|version] [appname]"
APPS.each {|app, port| status(app)}
exit
end