#!/bin/bash
# Version 5

timestamp() {
	date '+%Y.%m.%d %H:%M:%S'
}

# Create empty player list if not existing
# Params:
#   1: Instance name
createPlayerList() {
	PLAYERLIST=$(getInstancePath $1)/players.xml
	if [ ! -f $PLAYERLIST ]; then
		echo "<Players/>" > $PLAYERLIST
	fi
}

# Set all players for an instance to offline (on startup/shutdown)
# Params:
#   1: Instance name
setAllPlayersOffline() {
	PLAYERLIST=$(getInstancePath $1)/players.xml
	createPlayerList "$1"
	$XMLSTARLET ed -L \
		-u "/Players/Player/@online" -v "false" \
		$PLAYERLIST
}

# Handle a player connect for logging/tracking
# Params:
#   1: Instance name
#   2: Entity ID
#   3: Steam ID
#   4: Nick name
logPlayerConnect() {
	PLAYERLOG=$(getInstancePath $1)/players.log
	PLAYERLIST=$(getInstancePath $1)/players.xml
	ENTITYID=$2
	STEAMID=$3
	NICKNAME=$4

	echo "$(timestamp) +++ $ENTITYID $NICKNAME $STEAMID" >> $PLAYERLOG

	createPlayerList "$1"
	
	XPATHBASE="/Players/Player[@steamid='$STEAMID']"

	if [ -z $($XMLSTARLET sel -t -v "$XPATHBASE/@steamid" $PLAYERLIST) ]; then
		$XMLSTARLET ed -L \
			-s "/Players" -t elem -n "Player" -v "" \
			-i "/Players/Player[not(@steamid)]" -t attr -n "steamid" -v "$STEAMID" \
			-i "$XPATHBASE" -t attr -n "nick" -v "$NICKNAME" \
			-i "$XPATHBASE" -t attr -n "playtime" -v "0" \
			-i "$XPATHBASE" -t attr -n "logins" -v "1" \
			-i "$XPATHBASE" -t attr -n "lastlogin" -v "$(date '+%s')" \
			-i "$XPATHBASE" -t attr -n "online" -v "true" \
			-i "$XPATHBASE" -t attr -n "entityid" -v "$ENTITYID" \
			$PLAYERLIST
	else
		LOGINS=$($XMLSTARLET sel -t -v "$XPATHBASE/@logins" $PLAYERLIST)
		(( LOGINS++ ))
		$XMLSTARLET ed -L \
			-u "$XPATHBASE/@lastlogin" -v "$(date '+%s')" \
			-u "$XPATHBASE/@online" -v "true" \
			-u "$XPATHBASE/@entityid" -v "$ENTITYID" \
			-u "$XPATHBASE/@logins" -v "$LOGINS" \
			$PLAYERLIST
	fi
}

# Handle a player disconnect for logging/tracking
# Params:
#   1: Instance name
#   2: Entity ID
logPlayerDisconnect() {
	PLAYERLOG=$(getInstancePath $1)/players.log
	PLAYERLIST=$(getInstancePath $1)/players.xml
	ENTITYID=$2

	createPlayerList "$1"

	XPATHBASE="/Players/Player[@entityid='$ENTITYID'][@online='true']"

	if [ -f $PLAYERLIST ]; then
		if [ ! -z $($XMLSTARLET sel -t -v "$XPATHBASE/@steamid" $PLAYERLIST) ]; then
			NICKNAME=$($XMLSTARLET sel -t -v "$XPATHBASE/@nick" $PLAYERLIST)
			STEAMID=$($XMLSTARLET sel -t -v "$XPATHBASE/@steamid" $PLAYERLIST)
			LOGINTIME=$($XMLSTARLET sel -t -v "$XPATHBASE/@lastlogin" $PLAYERLIST)
			PLAYTIME=$($XMLSTARLET sel -t -v "$XPATHBASE/@playtime" $PLAYERLIST)
			NOW=$(date '+%s')
			PLAYTIME=$(( PLAYTIME + NOW - LOGINTIME ))
			$XMLSTARLET ed -L \
				-u "$XPATHBASE/@playtime" -v "$PLAYTIME" \
				-u "$XPATHBASE/@online" -v "false" \
				$PLAYERLIST
		fi
	fi

	echo "$(timestamp) --- $ENTITYID $NICKNAME $STEAMID" >> $PLAYERLOG
}

