#!/bin/bash
# Version 5

# Tries to start the 7dtd instance.

sdtdCommandStart() {
	if [ "$1" = "!" ]; then
		echo "Starting all instances:"
		for I in $(getInstanceList); do
			printf "%-*s: " 10 "$I"
			sdtdCommandStart $I
		done
		echo "All done"
		return
	fi

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

	if [ $(isRunning $1) -eq 0 ]; then
		if [ ! `pgrep Xvfb` ]; then
			echo "Xvfb not yet running. Starting..."
			su -c "/usr/bin/Xvfb :1 -screen 0 640x480x16" $SDTD_USER 2>&1 | grep -v "Could not init font path element" &
			sleep 3
		fi
		export DISPLAY=localhost:1.0
		
		setAllPlayersOffline $1
		rm $SDTD_BASE/engine/7DaysToDie_Data/output_log.txt
		
		for H in $(getHooksFor serverPreStart); do
			$H $INSTANCE
		done

		SSD_PID="--pidfile $(getInstancePath $1)/7dtd.pid --make-pidfile"
		SSD_DAEMON="--background --no-close"
		SSD_USER="--chuid $SDTD_USER:$SDTD_GROUP --user $SDTD_USER"
		OPTS="-quit -batchmode -nographics -configfile=$(getInstancePath $1)/config.xml -dedicated"
		
		start-stop-daemon --start $SSD_PID $SSD_DAEMON $SSD_USER --chdir $SDTD_BASE/engine --exec $WINE -- $SDTD_BASE/engine/7DaysToDie.exe $OPTS > $(getInstancePath $1)/stdout.log 2>&1
		sleep 1

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

		if [ $(isRunning $1) -eq 1 ]; then
			SSD_MONITOR_PID="--pidfile $(getInstancePath $1)/monitor.pid --make-pidfile"
			SSD_MONITOR_DAEMON="--background"
			start-stop-daemon --start $SSD_MONITOR_PID $SSD_MONITOR_DAEMON --exec "/usr/local/lib/7dtd/monitor-log.sh" -- "$1"
			echo "Done!"
		else
			echo "Failed!"
			rm -f $(getInstancePath $1)/7dtd.pid
		fi
	else
		echo "Instance $1 is already running"
	fi
}

sdtdCommandStartHelp() {
	echo "Usage: $(basename $0) start <instance>"
	echo
	echo "Starts the given instance."
	echo "If <instance> is \"!\" all defined instances are started."
}

sdtdCommandStartDescription() {
	echo "Start the given instance"
}

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

