#!/bin/bash
# Version 3

# Tries to stop the 7dtd instance given as first parameter.
# Returns:
#  0 : Done
#  1 : Was not running
#  2 : No instance name given
#  3 : No such instance

. /usr/local/bin/7dtd-common.sh
checkRootLoadConf

checkInstanceValid $1

res=$(isRunning $1)
if [ $res -eq 1 ]; then
	echo "Trying to gracefully shutdown..."
	tmp=$(telnetCommand $1 shutdown)
	echo "Waiting for server to shut down..."
	
	waittime=0
	maxwait=5
	until [ $(isRunning $1) -eq 0 ] || [ $waittime -eq $maxwait ]; do
		(( waittime++ ))
		sleep 1
		echo $waittime/$maxwait
	done
	
	if [ $(isRunning $1) -eq 1 ]; then
		echo "Failed, force closing server..."
		start-stop-daemon --stop --pidfile $(getInstancePath $1)/7dtd.pid
	fi
	rm $(getInstancePath $1)/7dtd.pid
	echo "Done"	
	exit 0
else
	echo "7dtd instance $1 is NOT running"
	exit 1
fi
