#!/bin/bash
# Version 5

# 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

sdtdCommandKill() {
	if [ "$1" = "!" ]; then
		echo "Stopping all instances:"
		for I in $(getInstanceList); do
			printf "%s:\n" "$I"
			sdtdCommandKill $I
			echo
		done
		echo "All done"
		return
	fi

	if [ $(isValidInstance $1) -eq 0 ]; then
		echo "No instance given or not a valid instance!"
		return
	fi

	res=$(isRunning $1)
	if [ $res -eq 1 ]; then
		for H in $(getHooksFor serverPreStop); do
			$H $INSTANCE
		done

		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

		$PKILL -TERM -P $(cat $(getInstancePath $1)/monitor.pid)
		rm $(getInstancePath $1)/monitor.pid
		setAllPlayersOffline $1

		rm $(getInstancePath $1)/7dtd.pid

		for H in $(getHooksFor serverPostStop); do
			$H $INSTANCE
		done

		echo "Done"	
	else
		echo "Instance $1 is NOT running"
	fi
}

sdtdCommandKillHelp() {
	echo "Usage: $(basename $0) kill <instance>"
	echo
	echo "Stops the given instance."
	echo "If <instance> is \"!\" all defined instances are stopped."
}

sdtdCommandKillDescription() {
	echo "Stop the given instance"
}

sdtdCommandKillExpects() {
	case $1 in
		2)
			echo "! $(getInstanceList)"
			;;
	esac
}

