#!/usr/bin/env ruby

# quick and dirty thin init script
#
# path for thin
thin = "/home/someuser/.rvm/gems/ruby-1.8.7-p72@global/bin/thin"
config = "config/config.ru"
# which dir to run from
path = "/srv/thisapp"

port = "9000"

# let's keep it trackable
log = "/var/log/thin.#{port}.log"
pid = "/var/log/thin.#{port}.pid"

case ARGV.first
        when 'status':
                if ( File.exist?(log) )
                        pid = `pidof thin`.chomp
                        log_pid = `cat #{log}`.chomp
                        if (pid.to_i == log_pid.to_i)
                                puts "running"
                        elsif (pid =~ /\d+/)
                                puts "running, but process does not match the pid in #{pid}!"
                        else
                                puts "not running, removing stale pid"
                                `rm -f #{pid}`
                        end
                else
                        puts "not running"
                end
        when 'start':
                system("#{thin} start --environment production --port #{port} -P #{pid} -l #{log} -d")
                puts "thin started"
        when 'stop':
                system("#{thin} stop -P #{pid}")
        when 'restart':
                system("#{thin} stop -P #{pid}")
                puts "waiting a couple of seconds to let everything die"
                sleep 5
                system("#{thin} start --environment production --port #{port} -P #{pid} -l #{log} -d")
                #system("#{thin} start -R #{config} -P #{pid} -l #{log} -d -c #{path}")
                puts "thin started"
        else
                puts "usage: $0 status|start|stop|restart"
end