#/bin/bash

BINDIR=$(cd $(dirname "$0"); pwd)
. ${BINDIR}/set-env.sh
if [ -z "$COH_HOME" ]; then
    echo Cannot run start-sim.sh, environment not correctly set
    echo Please examine bin/set-env.sh and set OBE_HOME and COH_HOME
    kill -2 $$
fi

CACHE_SERVER_KEYWORD="SimRunner"
TMP_FILE=/tmp/coherence.PIDLIST.SIM

ensure_kill_instance() {
    #kill remaining running cache servers run by user '$USER'
    user=$USER
    ps -u $user -o pid,args | grep $CACHE_SERVER_KEYWORD | grep -v grep > ${TMP_FILE}.stop

    cat ${TMP_FILE}.stop | while read pid prog
    do
    	kill -9 $pid > /dev/null 2>&1
    	#echo "Killed process '$prog' with ID '$pid'"
    done
    rm -f ${TMP_FILE}.stop
}

if [ -e ${TMP_FILE} ]; then 
PIDS=`cat ${TMP_FILE}`
echo Attempting to stop PIDS:$PIDS

arr=$(echo $PIDS| tr " " "\n")

for PID in $arr
do
    kill -0 $PID > /dev/null 2>&1
    STATUS=$?
    if [ "$STATUS" = "1" ]
    then
       echo "Sim $PID not running"
    else
       echo "Stopping sim $PID"
       kill -9 $PID > /dev/null
    fi
done

ensure_kill_instance
rm -f ${TMP_FILE}

else
echo No simulations appear to be running.

fi