#!/bin/bash
#
# runSeasideGems [start | stop | restart]
#
# The default setup is to run 4 vms ... three listening on ports 9001-9003
# as Seaside adaptor gems and one maintenance vm
#
# 
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: runem (start|stop|restart)"
            ;;
esac

