#!/bin/bash
# Version 1

# Provides common functions for 7dtd-scripts. Not intended to be run directly.

# Check if the script is run as root (exit otherwise) and load global config
checkRootLoadConf() {
	if [ `id -u` -ne 0 ]; then
		echo "This script has to be run as root!"
		exit 10
	fi
	. /etc/7dtd.conf
}

# Get the config path for the given instance
# Params:
#   1: Instance name
# Returns:
#   Config path for instance
getInstancePath() {
	echo $SDTD_BASE/instances/$1
}

# Check if the given instance name is an existing instance
# On failure exit the script!
# Params:
#   1: Instance name
checkInstance() {
	if [ -z $1 ]; then
		echo "No instance given!"
		exit 2
	fi
	if [ ! -d $(getInstancePath $1) ]; then
		echo "Instance $1 does not exist!"
		exit 3
	fi
}

# Check if the given instance is currently running
# Params:
#   1: Instance name
# Returns:
#   0 = not running
#   1 = running
isRunning() {
	start-stop-daemon --status --pidfile $(getInstancePath $1)/7dtd.pid
	if [ $? -eq 0 ]; then
		echo 1
	else
		echo 0
	fi
}

# Get a single value from a serverconfig
# Params:
#   1: Instance name
#   2: Property name
# Returns:
#   Property value
getConfigValue() {
	CONF=$(getInstancePath $1)/serverconfig.xml
	xmllint --xpath "string(/ServerSettings/property[@name='$2']/@value)" $CONF
}

# Send a single command to the telnet port
# Params:
#   1: Instance name
#   2: Command
# Returns:
#   String of telnet output
telnetCommand() {
	TEL_ENABLED=$(getConfigValue $1 TelnetEnabled)
	TEL_PORT=$(getConfigValue $1 TelnetPort)
	TEL_PASS=$(getConfigValue $1 TelnetPassword)	
	if [ "$TEL_ENABLED" = "true" ] && [ -n "$TEL_PASS" ]; then
		echo -e "$TEL_PASS\n$2\nexit" | nc -q 2 127.0.0.1 $TEL_PORT
	else
		echo "Telnet not enabled or no password set."
	fi
}
