#!/bin/sh
#
# LambdaMoo init script, by Joey Hess, <joeyh@master.debian.org>
#
# This tag tells debstd that we do not wish to restart 
# on upgrades: NO_RESTART_ON_UPGRADE 
#
# Edit /etc/lambdamoo.conf to change LambdaMoo's configuration.

test -f /usr/sbin/startmoo || exit 0
test -f /etc/lambdamoo.conf || exit 0

# Read config file.
source /etc/lambdamoo.conf

# Sanity check on config file.
if [ "$PORT" = "" ] || [ "$DBFILE" = "" ] || [ "$LOGFILE" = "" ] || \
   [ "$TIMEOUT" = "" ]; then
	echo "LambdaMoo: bad /etc/lambdamoo.conf!" ;
	exit
fi

# See how we were called.
case "$1" in
  start)
	echo -n "Starting LambdaMoo server: lambdamoo"
	start-stop-daemon --start --quiet --exec /usr/sbin/lambdamoo \
		--startas /usr/sbin/startmoo -- $DBFILE $PORT $LOGFILE
	echo "."
	;;
  stop)
	echo -n "Stopping LambdaMoo server: lambdamoo"
	if [ "`pidof /usr/sbin/lambdamoo`" ] ; then
		# Signal 2 means dump db and die.
		start-stop-daemon --stop --signal 2 --exec /usr/sbin/lambdamoo

		# Wait until the timeout for the server to die.
		count=$TIMEOUT
		while ([ $count != 0 ]) do
			let count=$count-1
			if [ "`pidof /usr/sbin/lambdamoo`" ] ; then
				sleep 1
			else
				count=0
			fi
			echo -n .
		done

		# If it's not dead yet, kill it.
		if [ "`pidof /usr/sbin/lambdamoo`" ] ; then
			echo -n " TIMEOUT!"
			kill -KILL `pidof /usr/sbin/lambdamoo`
		else
			echo "done."
		fi
	else
		echo " not running.";
	fi

	;;
  restart)
	# There doesn't appear to be a better way (like a signal we could send.)
	$0 stop
	$0 start
	;;
  *)
	echo "Usage: /etc/init.d/lambdamoo {start|stop|restart}"
	exit 1
esac

exit 0
