#!/bin/sh
#
#	Startmush - Kick off the netmush process.
#
PATH=/usr/ucb:/bin:/usr/bin:.; export PATH
#
. mush.config
#
#	Make sure there isn't aready a MUSH running.
#
if [ -r mush.pid ]; then
	oldpid=`cat mush.pid`
	if [ $oldpid -gt 1 ]; then
		nmush=`ps | grep $oldpid | grep netmush | wc -l`
		if [ $nmush -gt 0 ]; then
			echo "The MUSH already seems to be running."
			exit 0
		fi
	fi
fi

#
#	Make sure the indexes are up-to-date.
#
./Index

echo "Checking for database files and creating backups of old files."

#
#	Refuse to start if a restart.db is present.
#
if [ -r restart.db ]; then
    echo "There is a restart database, restart.db, present."
    echo "Please delete it before attempting to start the MUSH."
    exit 1
fi

#
#	Refuse to start if CORRUPT or KILLED databases are present.
#
if [ -r $DATA/$INPUT_DB.KILLED -o -r $DATA/$INPUT_DB.CORRUPT ]; then
	echo "There is a CORRUPT or KILLED database present." 
	echo "You should salvage what you can before continuing."
	exit 1
fi

#
#	Check for a panic dump.  If there is one and it is good, copy
#	it on top of the last checkpoint DB written by mush.  If it is bad,
#	just delete it.
#
if [ -r $DATA/$CRASH_DB ]; then
	end="`tail -1 $DATA/$CRASH_DB`"
	if [ "$end" = "***END OF DUMP***" ]; then
		mv $DATA/$CRASH_DB $DATA/$NEW_DB
	else
		rm $DATA/$CRASH_DB
		echo "Warning: PANIC dump corrupt using older db."
		echo "Warning: PANIC dump failed on "`date` | mail $OWNER
	fi
fi

#
#	Save a copy of the previous input databases.
#
if [ -r $DATA/$INPUT_DB ]; then
	mv -f $DATA/$INPUT_DB $DATA/$SAVE_DB
else
	echo "No previous input database."
fi

if [ -r "comsys.db" ]; then
	cp -f comsys.db comsys.db.old
elif [ -r "$DATA/comsys.db" ]; then
	cp -f $DATA/comsys.db $DATA/comsys.db.old
else
	echo "No previous comsys database."
fi

if [ -r "mail.db" ]; then
	cp -f mail.db mail.db.old
elif [ -r "$DATA/mail.db" ]; then
	cp -f $DATA/mail.db $DATA/mail.db.old
else
	echo "No previous mail database."
fi

#	If we have a good checkpoint database, make it the input database.
#	If not, use the backup of the input database.
#
if [ -r $DATA/$NEW_DB ]; then
	mv $DATA/$NEW_DB $DATA/$INPUT_DB
else
	if [ -r $DATA/$SAVE_DB ]; then
		echo "No recent checkpoint db. Using older db."
		cp $DATA/$SAVE_DB $DATA/$INPUT_DB
	else
		echo "No recent db. Will initialize new database."
		make_db="-s"
	fi
fi
#
#	Remove the start db if there is one.
#
if [ -r restart.db ]; then
	rm -f restart.db
fi
#
#	Cleanup the old logfiles.
#
./Logclean
#
#	Kick off MUSH
#
touch $LOGNAME
(nohup $BIN/netmush $make_db -c $GAMENAME.conf -l $LOGNAME >>$LOGNAME 2>&1 & echo $! >mush.pid)
echo "Process `cat mush.pid`"
tail -f $LOGNAME | awk '{ print $0 }; /Cleanup completed/ { exit };'
