#!/bin/sh

# This shell script is run via ``at'' and makes sure empire is up.  If
# it detects empire is down (e.g., at reboot time), it will bring it
# back up and mail a note to the maintainer.  It also copies EMP/DATA into
# EMP/BAK/DATA every morning at 5:45 to avoid losing the whole game to 
# random bugs.  Two complete sets of backups are kept around so a bug
# manifesting at 5:44 won't screw everyone over.

EMPIRE=/yale/games/lib/empire/EMP
LOGFILE=$EMPIRE/empwatch_log
DEITY=metcalf

date="`date`"
next=`expr \( substr "$date" 12 2 \) + 1`
if [ $next -ge 24 ]; then next=0; fi

exec >> $LOGFILE 2>&1
date
cd $EMPIRE

skill -0 empserver && skill -0 killd && skill -0 empire_tmserver
if [ $? -ne 0 ]
then
	echo "restarting empire at `date`"
	skill empserver killd empire_tmserver emp_serv
	../BIN/esck -y
	cd $EMPIRE/BIN
	nice -1 empserver &
	nice -1 empire_tmserver &
	echo "empire restarted at `date`"
	tail $LOGFILE | /bin/mail $DEITY
fi

if [ $next -eq 6 ]
then
	cd $EMPIRE
	rm -rf BAK/DATA.old
	if [ -r BAK/DATA ]; then mv BAK/DATA BAK/DATA.old; fi
	cp -r DATA BAK
	echo "empire backed up at `date`"
	if [ -r BAK/DATA.old ]; then echo -n "`du BAK/DATA.old`; "; fi
	echo "`du BAK/DATA`"
	../BIN/esck -n | /bin/mail $DEITY
fi

at -s ${next}:45 $EMPIRE/empwatch
