#! /bin/sh

#############################################################################
# This script kills the Daylight Thor, Merlin, and RT servers, using
# the logfiles defined by environment variables DY_THOR_LOG_FILE and
# DY_MERLIN_LOG_FILE to determine the process ids.  Thus, these env
# variables must have been set correctly when the servers were started.
#
# (See also script START_DCIS_SERVERS.)
#############################################################################

if [ ! "$DY_MERLIN_LOG_FILE" ]; then
  echo "DY_MERLIN_LOG_FILE not defined; can't find pid."
  exit 1
fi
if [ ! "$DY_THOR_LOG_FILE" ]; then
  echo "DY_THOR_LOG_FILE not defined; can't find pid."
  exit 1
fi
if [ ! "$DY_TOOLSERVER_LOG_FILE" ]; then
  echo "DY_TOOLSERVER_LOG_FILE not defined; can't find pid."
  exit 1
fi

mpid=`grep pid $DY_MERLIN_LOG_FILE | sed -e "s/^.*pid = //" -e "s/ //g"`
case "$mpid" in
  [0-9][0-9]*)	echo "Merlinserver pid = $mpid" ;;
  ?)	mpid="";
	echo "Can't determine Merlinserver pid." ;;
esac

tpid=`grep pid $DY_THOR_LOG_FILE | sed -e "s/^.*pid = //" -e "s/ //g"`
case "$tpid" in
  [0-9][0-9]*)	echo "Thorserver pid = $tpid" ;;
  ?)	tpid="";
	echo "Can't determine Thorserver pid." ;;
esac

rpid=`grep "pid =" $DY_TOOLSERVER_LOG_FILE \
	| tail -1 \
	| sed -e "s/^.*pid = //" -e "s/ //g"`
case "$rpid" in
  [0-9][0-9]*) echo "Daytoolserver pid = $rpid" ;;
  ?)	rpid="";
	echo "Can't determine Daytoolserver pid." ;;
esac

echo "Now evicting all Thor users..."
sthorman -input $HOME/utils/evict.sthor > /dev/null

if [ "$mpid" ]; then
  echo "Killing Merlinserver ..."
  kill $mpid
else
  echo "Merlinserver NOT killed ..."
fi

if [ "$tpid" ]; then
  echo "Killing Thorserver ..."
  kill $tpid
else
  echo "Thorserver NOT killed ..."
fi

if [ "$rpid" ]; then
  echo "Killing Daytoolserver ..."
  kill $rpid
else
  echo "Daytoolserver NOT killed ..."
fi

echo "Done."
