#!/bin/sh
#
# Perlmoo init script, by Joey Hess, <joeyh@master.debian.org>

# How long to wait for the server to die after asking it to, in seconds
TIMEOUT=600

# We don't want it to load up any conffile that happens to be in the current
# directory.
cd /

# See how we were called.
case "$1" in
  start)
	echo -n "Starting Perlmoo server: perlmoo"

	# Check if there is a process to match what's in the pid file,
        # by sending signal 0, which has no effect. This also checks to see
        # if there is a pid file at all, btw.
        if start-stop-daemon --quiet --stop --signal 0 \
		--pidfile /var/run/perlmoo.pid --name perlmoo 2>/dev/null
	then
		echo " already running."
		exit
	fi

	start-stop-daemon --start --quiet \
		--exec /usr/bin/perlmoo \
		--startas /usr/bin/perlmoo -- --daemon --pidfile=/var/run/perlmoo.pid
		>/dev/null 2>/dev/null </dev/null &\
	echo "."
	;;
  stop)
	echo -n "Stopping Perlmoo server: perlmoo"
	# Check if there is a process to match what's in the pid file,
	# by sending signal 0, which has no effect. This also checks to see
	# if there is a pid file at all, btw.
	if start-stop-daemon --quiet --stop --signal 0 \
		--pidfile /var/run/perlmoo.pid --name perlmoo 2>/dev/null
	then
		# Signal 2 means dump db and die.
		start-stop-daemon --quiet --stop --signal 2 \
			--name perlmoo \
			--pidfile /var/run/perlmoo.pid

		# Wait until the timeout for the server to die.
		count=$TIMEOUT
		newfile=no
		pid=`cat /var/run/perlmoo.pid`
		while ([ $count != 0 ]) do
			let count=$count-1
			if kill -0 "$pid" 2>/dev/null ; then
				sleep 1
			else
				count=0
			fi
			echo -n .
		done

		# If it's not dead yet, kill it.
		if  kill -0 "$pid" 2>/dev/null ; then
			echo " TIMEOUT!"
			start-stop-daemon --quiet --stop \
				-exec /usr/sbin/perlmoo \
				--pidfile /var/run/perlmoo.pid \
				--name perlmoo 2>/dev/null
		else
			echo "done."
		fi
	else
		echo " not running.";
	fi

	rm -f /var/run/perlmoo.pid

	;;
  force-reload|restart)
	$0 stop
	$0 start
	;;
  *)
	echo "Usage: /etc/init.d/perlmoo {start|stop|restart|force-reload}"
	exit 1
esac

exit 0
