#!/bin/bash
#
# runSeasideGems30 [start | stop | restart] <label> "<port numbers>"
# 
#  launch a single gem using startSeaside30_Adaptor (which controls which adaptor is run)
#    the <label> is ued in log files and error messages
#    the <port numbers> is a list of port numbers. A seaside gem is launched for each port in list.
#
#    see WAGemStoneRunSeasideGems for more details
# 
SeasideAdaptor="$2" 
PORTS="$3"

topaz_start()
{
    echo "Starting Gems...."
    for port in $PORTS; do
        if [ -e $GEMSTONE_DATADIR/${SeasideAdaptor}_server-${port}.pid ]; then
            echo "PID file for topaz on port $port already exists (already running?), try using the stop command first."
            continue
        fi
        echo "	Starting ${SeasideAdaptor} gem on port $port"
        $GEMSTONE/seaside/bin/startSeaside30_Adaptor $SeasideAdaptor $port >& ${GEMSTONE_LOGDIR}/${SeasideAdaptor}_start-${port}.log &
    done

    if [ -e $GEMSTONE_DATADIR/maintenance_gem.pid ]; then
            echo "PID file for maintenance gem already exists (already running?), try using the stop command first."
    else
        echo "	Starting maintenance gem"
        $GEMSTONE/seaside/bin/startMaintenance30 >& ${GEMSTONE_LOGDIR}/maintenance_start.log &
    fi
}

topaz_stop()
{
    echo "Stopping Gems..."
    for port in $PORTS; do
        pidfile="$GEMSTONE_DATADIR/${SeasideAdaptor}_server-${port}.pid"

        if [ -e $pidfile ]; then
            pid=`cat $pidfile`
            echo "   Stopping ${SeasideAdaptor} topaz PID $pid running on port $port"
            kill $pid
            rm $pidfile
        else
            echo "   No PID file found for gem on port $port, not running?"
        fi
    done

    pidfile=$GEMSTONE_DATADIR/maintenance_gem.pid

    if [ -e $pidfile ]; then
        pid=`cat $pidfile`
        echo "   Stopping maintenance gem PID $pid"
        kill $pid
        rm $pidfile
    else
        echo "   No PID file for for the maintenance gem, not running?"
    fi
    sleep 2
}

topaz_restart()
{
    echo "Restarting Gems..."
    topaz_stop
    topaz_start
}

case "$1" in

    start)
           topaz_start 
            ;;
    restart)
            topaz_restart
            ;;
    stop)
            topaz_stop
            ;;
    *)
            echo "Usage: runSeasdideGems30 (start|stop|restart) <label> \"<port numbers>\""
            ;;
esac

