#! /bin/bash
# Script for starting/stopping Pioneers Meta Server
# Author: Tomas Kelemen <tomas.kelemen@mail.t-com.sk>
#
### BEGIN INIT INFO
# Provides: pio-server
# Required-Start: $local_fs $remote_fs $network
# Required-Stop:  $local_fs $remote_fs $network
# Default-Start:  3 5
# Default-Stop:   0 1 2 6
# Description:    Start Pioneers Meta server for Pioneers,
#       Settlers of Catan board game, http://pio.sourceforge.net/
# Short-Description:    Start Pioneers Meta server for Pioneers,
### END INIT INFO

PATH="/bin:/usr/bin"
# Binary of the meta server incl. full path
PIOBIN="/usr/bin/pioneers-metaserver"
# Name of the binary for separate hosted games
GAMEBIN="pioneers-server-console"

# Load functions
. /etc/rc.status

# Reset the status of this proces
rc_reset

# Does the configuration file exist?
if [ -f /etc/pio-server ]; then
	. /etc/pio-server
else
	echo "Configuration file (/etc/pio-server) was not found!"
	echo "Run the Pioneers server manually or create this file."
	rc_failed 1
	rc_status -v
fi

# Do we have the binnary?
if [ ! -x $PIOBIN ] ; then
	echo "Binary $PIOBIN not found! Exiting!"
	exit 5
fi

case "$1" in
	start)
		# Are there still some games running?
		if ps -C $GAMEBIN > /dev/null ; then
			echo "There are running games. Stop them first ($0 clean)!"
			exit 5
		fi
		echo -n "Starting Pioneers Meta Server"
		startproc -u games -g games $PIOBIN --daemon --servername=$SERVERNAME --port-range=$PORTS
		rc_status -v
		;;
	stop)
		if ps -C $GAMEBIN > /dev/null ; then
			echo -n "Shutting down running games first ... "
			killall $GAMEBIN
			if [ $? = 0 ] ; then
				echo "done."
			else
				echo "error!"
			fi
		fi
		echo -n "Shutting down Pioneers Meta Server"
		killproc -TERM $PIOBIN
		rc_status -v
		;;
	restart)
		$0 stop
		$0 start
		rc_status
		;;
	reload)
		$0 stop
		$0 start
		rc_status
		;;
	clean)
		if ps -C $GAMEBIN > /dev/null ; then
			echo -n "Shutting down running games ... "
			killall $GAMEBIN
			if [ $? = 0 ] ; then
				echo "done."
			else
				echo "error!"
			fi
		else
			echo "No games are running."
		fi
		;;
	status)
		# How many games are currently running?
		echo -n "Currently running "
		numgames="$((`ps -C $GAMEBIN | wc -l`-1))"
		echo "$numgames game(s)."
		echo -n "Checking status of Pioneers Meta Server"
		checkproc $PIOBIN
		rc_status -v
		;;
	*)
		echo "Usage: $0 {start|stop|restart|reload|clean|status}"
		exit 1
		;;

esac
rc_exit
