#!/bin/sh

### BEGIN INIT INFO
# Provides:          7dtd-server
# Required-Start:    $remote_fs
# Required-Stop:     $remote_fs
# Should-Start:      $named
# Should-Stop:       $named
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: 7 Days to Die server
# Description:       Starts a 7 Days to Die server
### END INIT INFO

. /etc/7dtd.conf

NAME="7DtD"
SCREENREF="sdtd"
BINARYPATH=$SDTD_ROOT
USER=$SDTD_USER
RUNTIME=$WINE
BINARYNAME=7DaysToDie.exe
PIDFILE="7dtd-server.pid"

OPTS="-quit -batchmode -nographics -configfile=../serverconfig.xml -dedicated"

cd "$BINARYPATH"

case "$1" in
    start)
        echo -n "Starting the $NAME server... "
        if [ ! `pgrep Xvfb` ]; then
        	su -c "/usr/bin/Xvfb :1 -screen 0 640x480x16" sdtd &
        	sleep 3
        fi
	if [ -e "$BINARYNAME" ]; then
	    if [ `pgrep $BINARYNAME` ]; then
	        echo "Already running!"
	    else
	    	export DISPLAY=localhost:1.0
                start-stop-daemon --start --pidfile $SDTD_ROOT/$PIDFILE --background --make-pidfile --chuid $USER --user $USER --chdir $BINARYPATH --exec "/usr/bin/screen" -- -D -m -S $SCREENREF $RUNTIME $BINARYPATH/$BINARYNAME $OPTS
                sleep 1
            fi
        else
            echo "Could not find binary, aborting!"
            exit 5
        fi
        if [ `pgrep -F $SDTD_ROOT/$PIDFILE` ]; then
            echo "Done!"
        else
            echo "Failed!"
            rm -f $SDTD_ROOT/$PIDFILE
        fi
    ;;
    stop)
    	start-stop-daemon --status --pidfile $SDTD_ROOT/$PIDFILE
        if [ $? -eq 0 ]; then
            echo -n "Stopping the $NAME server... "
            if [ "$SDTD_TELNET_ENABLED" = "true" ] && [ -n "$SDTD_TELNET_PASSWORD" ]; then
                echo "$SDTD_TELNET_PASSWORD\nshutdown" | nc -q 2 127.0.0.1 $SDTD_TELNET_PORT
                sleep 5
            else
                echo "Telnet not enabled or no password set. No graceful shutdown!"
            fi
            start-stop-daemon --stop --pidfile $SDTD_ROOT/$PIDFILE
            rm $SDTD_ROOT/$PIDFILE
            echo "Done!"
        else
            echo "$NAME not running"
        fi
    ;;
    status)
    	start-stop-daemon --status --pidfile $SDTD_ROOT/$PIDFILE
        if [ $? -eq 0 ]; then
            echo "$NAME server is running"
        else
            echo "$NAME server not running"
        fi
    ;;
    *)
        echo "Usage: ${0} {start|stop|status}"
        exit 2
esac
exit 0
