#!/bin/bash

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

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

INSTANCE=$1
LOG=$(getInstancePath $INSTANCE)/output.log
CHATLOG=$(getInstancePath $INSTANCE)/chat.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" "$3"

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

handleDisconnect() {
	logPlayerDisconnect $INSTANCE "$2"

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

handleChat() {
	echo "$(timestamp): $1" >> $CHATLOG
	
	for H in $(getHooksFor chat); do
		$H $INSTANCE "$1"
	done
}

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

sleep 5

NOBUF="stdbuf -e0 -o0"

$NOBUF tail -n 5000 -F $(getInstancePath $INSTANCE)/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
			entityId=$(expr "$line" : 'RequestToSpawnPlayer: \([0-9]*\), [0-9]*, .*, [0-9]*$')
			playerId=$(expr "$line" : 'RequestToSpawnPlayer: [0-9]*, \([0-9]*\), .*, [0-9]*$')
			playerName=$(expr "$line" : 'RequestToSpawnPlayer: [0-9]*, [0-9]*, \(.*\), [0-9]*$')
			unknown=$(expr "$line" : 'RequestToSpawnPlayer: [0-9]*, [0-9]*, .*, \([0-9]*\)$')
			sleep 1
			handleConnect "$playerId" "$entityId" "$playerName"
			unset entityId playerId playerName unknown
		else
		if [ -n "$(echo "$line" | grep '^Removing player with id ')" ]; then
			playerId=$(expr "$line" : 'Removing player with id clientId=\([0-9]*\), entityId=[0-9]*$')
			entityId=$(expr "$line" : 'Removing player with id clientId=[0-9]*, entityId=\([0-9]*\)$')
			handleDisconnect "$playerId" "$entityId"
			unset playerId entityId
		else
		if [ -n "$(echo "$line" | grep -E '^GMSG: .+')" ]; then
			msg=$(expr "$line" : 'GMSG: \(.*\)$')
			handleChat "$msg"
			unset msg
		fi
		fi
		fi
	fi
done
