#!/bin/bash

#   Copyright 2016 Christian 'Alloc' Illy
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.



#################################
## Generic worker functions


# Set parameters for current instance that have forced values:
#  - TelnetEnabled must be set so that management scripts can work
#  - AdminFileName is made to point to the local instance admins.xml
#  - SaveGameFolder is made to point to the instance folder
#  - UserDataFolder (for GeneratedWorlds) is made to point to the <user home directory>/serverdata/
# Params:
#   1: Instance name
configSetAutoParameters() {
	setConfigValue "$1" "TelnetEnabled" "true"
	setConfigValue "$1" "AdminFileName" "admins.xml"
	setConfigValue "$1" "SaveGameFolder" "$(getInstancePath "$1")"
	setConfigValue "$1" "UserDataFolder" "$SDTD_BASE/serverdata"
}

# Query for an instance name (will be saved in $INSTANCE)
readInstanceName() {
	until [ $(isValidInstanceName "$INSTANCE") -eq 1 ]; do
		read -p "Instance name: " INSTANCE
		if [ $(isValidInstanceName "$INSTANCE") -eq 0 ]; then
			echo "Invalid instance name, may only contain:"
			echo " - letters (A-Z / a-z)"
			echo " - digits (0-9)"
			echo " - underscores (_)"
			echo " - hyphens (-)"
		fi
	done
}


# Check if the config template exists
# Returns:
#   0/1: no/yes
configTemplateExists() {
	if [ -f $SDTD_BASE/templates/config.xml ]; 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() {
	local CONF=$(getInstancePath $1)/config.xml
	$XMLSTARLET sel -t -v "/ServerSettings/property[@name='$2']/@value" $CONF
}

# Update a single value in a serverconfig
# Params:
#   1: Instance name
#   2: Property name
#   3: New value
setConfigValue() {
	local CONF=$(getInstancePath $1)/config.xml
	$XMLSTARLET ed -L -u "/ServerSettings/property[@name='$2']/@value" -v "$3" $CONF
}
