#!/bin/bash
# Version 3

# Tries to start the 7dtd instance given as first parameter.
# Returns:
#  0 : Done
#  1 : Was already running
#  2 : No instance name given
#  3 : No such instance
#  5 : Unknown error when starting engine

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

checkInstanceValid $1

res=$(isRunning $1)
if [ $res -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
	
	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_ROOT --exec $WINE -- $SDTD_ROOT/7DaysToDie.exe $OPTS > $(getInstancePath $1)/stdout.log 2>&1
	sleep 1
	res=$(isRunning $1)
	if [ $res -eq 1 ]; then
		echo "Done!"
		exit 0
	else
		echo "Failed!"
		rm -f $(getInstancePath $1)/7dtd.pid
		exit 5
	fi
else
	echo "7dtd instance $1 is already running"
	exit 1
fi
