#! /bin/bash
# Copyright (c) 2004 TeamSpeak team   All rights reserved.
#
# Author: pwk.linuxfan 2004
#

case "$1" in
	start)
		if [ -e tsserver2.pid ]; then
			echo "tsserver2.pid already exists...server already started ?";
			echo "If you are sure the server is not running, delete tsserver2.pid"
			exit 1
		else
			if [ "$UID" = "0" ]; then
				echo WARNING ! For security reasons we advise: DO NOT RUN THE SERVER AS ROOT
				for c in $(seq 1 10); do
					echo -n "!"
					sleep 1
				done
				echo !
			fi
			echo "starting the teamspeak2 server"
			if [ -e server_linux ]; then
				if [ ! -x server_linux ]; then
					echo "server_linux is not executable, trying to set it"
					chmod u+x server_linux
				fi
				if [ -x server_linux ]; then
					./server_linux -PID=tsserver2.pid
				else
					echo "server_linux is not executable, fix this"
					exit 4
				fi
			else
				echo "Couldnt find server_linux"
				exit 5
			fi
		fi
	;;
    stop)
		if [ -e tsserver2.pid ]; then
			echo -n "stopping the teamspeak2 server"
			if ( kill -TERM `cat tsserver2.pid` ); then
				for c in $(seq 1 300); do
					if [ -e tsserver2.pid ]; then
						echo -n "."
						sleep 1
					fi
				done
			fi
			if [ -e tsserver2.pid ]; then
				echo "server does not shutdown cleanly - killing"
				kill -KILL `cat tsserver2.pid`
				rm tsserver2.pid
				sleep 5
			else
				echo "done"
			fi
		else
			echo "tsserver2.pid is missing, no started server ?"
			exit 7
		fi
	;;
	restart)
		$0 stop && $0 start || exit 1
	;;
	status)
		if [ -e tsserver2.pid ]; then
			echo "the server seems to be running"
			exit 0
		else
			echo "the server seems to be stopped"
			exit 3
		fi
	;;
	passwords)
		if [ -e server.log ]; then
			date=$(cat server.log | grep "admin account info: username: admin" | tail -n 1 | sed "s/^\([0-9]\+-[0-9]\+-[0-9]\+ [0-9]\+:[0-9]\+:[0-9]\+\).*$/\1/")
			spass=$(cat server.log | grep "superadmin account info: username: superadmin" | tail -n 1 | sed "s/^.*username: superadmin password: \([a-z0-9]\+\).*$/\1/")
			pass=$(cat server.log | grep "admin account info: username: admin" | tail -n 1 | sed "s/^.*username: admin password: \([a-z0-9]\+\).*$/\1/")
			echo "Following passwords were generated on $date"
			echo "superadmin = \"$spass\""
			echo "admin      = \"$pass\""
		else
			echo "server.log not found, maybe you did not start the server yet ?" 
			exit 1
		fi
	;;
	*)
		echo "Usage: $0 {start|stop|restart|status|passwords}"
		exit 2
esac
exit 0
