#!/bin/bash
# Version 4

. /usr/local/lib/7dtd/common.sh
checkRootLoadConf

if [ $(isValidInstance $1) -eq 0 ]; then
	echo "No instance given or not a valid instance!"
	return
fi

INSTANCE=$1
LOG=$(getInstancePath $INSTANCE)/output.log

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

handleConnect() {
	tel=$(telnetCommand $INSTANCE lp)
	playerline=$(echo "$tel" | tr -d '\r' | grep "id=$2,")
	nickname=$(echo "$playerline" | sed -r 's/^.* id=[0-9]*, ([^,]*), pos=.*$/\1/')
	steamid=$(echo "$playerline" | sed -r 's/^.*, health=[0-9]*, ([0-9]*)$/\1/')
	
	if [ -z "$steamid" ]; then
		return
	fi

	logPlayerConnect $INSTANCE $2 $steamid $nickname

	for H in $(getHooksFor playerConnect); do
		$H $INSTANCE $1 $2 $nickname $steamid
	done
}

handleDisconnect() {
	logPlayerDisconnect $INSTANCE $2

	for H in $(getHooksFor playerDisconnect); do
		$H $INSTANCE $1 $2 $NICKNAME $STEAMID
	done
}

echo >> $LOG
echo >> $LOG
echo "Starting instance $INSTANCE at $(timestamp)" >> $LOG
echo >> $LOG

NOBUF="stdbuf -e0 -o0"

$NOBUF tail -n 5000 -F $SDTD_BASE/engine/7DaysToDie_Data/output_log.txt |
$NOBUF tr '\\' '/' |
$NOBUF tr -d '\r' |
$NOBUF grep -v "^(Filename: " |
while read line ; do
	if [ -n "$line" ]; then
		echo "$(timestamp): $line" >> $LOG
		if [ -n "$(echo "$line" | grep '^RequestToSpawnPlayer:')" ]; then
			read entityId playerId playerName unknown <<< "$(echo $line | sed -r 's/^RequestToSpawnPlayer: (.*), (.*), (.*), (.*)$/\1 \2 \3 \4/')"
			sleep 1
			handleConnect $playerId $entityId $playerName
			unset entityId playerId playerName unknown
		fi
		if [ -n "$(echo "$line" | grep '^Removing player with id ')" ]; then
			read playerId entityId <<< "$(echo $line | sed -r 's/^Removing player with id clientId=(.*), entityId=(.*)$/\1 \2/')"
			handleDisconnect $playerId $entityId
			unset playerId entityId
		fi
	fi
done
