#! /bin/sh
## start and stop the net tamagotchi server.

PATH=/bin:/sbin:/usr/bin:/usr/sbin
NAME=tamad
DAEMON=/usr/games/${NAME}

test -x ${DAEMON} || exit 0

case "$1" in
	start)
		echo -n "Starting net tamagotchi server: tamad"
		cd /var/lib/tama/ || exit 1
		umask 077

		# 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 \
			--chdir /var/lib/tama \
			--pidfile /var/run/tama.pid --name ${NAME} \
			2>/dev/null
		then
			echo " already running."
			exit
		fi

		start-stop-daemon --chuid games --start --quiet \
			--chdir /var/lib/tama \
			--exec ${DAEMON} --pidfile /var/run/tama.pid \
			>> /var/log/tama.log 2>&1 &

		echo $! > /var/run/tama.pid
		echo "."
		;;
	stop)
		echo -n "Stopping net tamagotchi server: tamad"
		# 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 \
			--chdir /var/lib/tama \
			--pidfile /var/run/tama.pid --user games \
			--name ${NAME} 2>/dev/null
		then
			start-stop-daemon --quiet --stop \
				--pidfile /var/run/tama.pid \
				--user games \
				--name ${NAME} 
			rm -f /var/run/tama.pid
			echo "."
		else
			echo " not running."
		fi
		;;
	restart|force-reload)
		$0 stop
		$0 start
		;;
	*)
		echo "Usage: /etc/init.d/tama {start|stop|restart|force-reload}"
		exit 1
esac

exit 0
