#!/usr/bin/env bash

#rails project home dir
#!!Change acc to your needs
cd /home/rails/test/current

#Ports mongrels are running on
#!!Change acc to your needs
for PORT in 8000 8001 8002
do
        #the location of our pid-files
        #!!Change acc to your needs
        PF=/var/run/mongrel/mongrel.$PORT.pid

        #pidfile exists ?
        if [ -e $PF ]; then
                PR=$(cat $PF)

                #process still running ?
                if ps $PR > /dev/null 2>&1; then
                        echo "$PF $PR Running - killing"
                        kill $PR
                        while ps $PR > /dev/null 2>&1; do
                                echo "$PR still running"
                                sleep 1
                        done
                        echo "$PR killed"
                else
                        echo "$PF $PR Not Running - deleting pidfile"
                        rm -f $PF
                fi
        else
                echo "$PF does not exist"
        fi

        #check if a command containing $PORT.pid is still running
        #in case process is still active but pidfile was not found
        if ps ax|grep $PORT.[p]id > /dev/null 2>&1; then
                echo "!!! But process containing $PORT.pid running !!!"
                echo "!!! NOT auto-restarting, Manual intervention necessary !!!"
        else
                echo "Restarting port $PORT"
                #mongrel start cmd
                #!!Change acc to your needs
                mongrel_rails start -d -e production -p $PORT -P $PF
                sleep 1
                #check if process is actually running now (could also be done by pidfile based check)
                while ! ps ax|grep $PORT.[p]id > /dev/null 2>&1; do
                        echo "Not Running"
                done
				fi

done

