#!/bin/bash

####################
###### CONFIG ######
####################
inputPath="./banner-input.jpg"  #background used for text
inputEmpty="./banner-empty.jpg" #copied when no players online
outputPath="/var/www/files.raidworld.net/teamspeak/Banner_dynamic.jpg"
#fontPath="./FatFrank.otf"
fontPath="./integral-cf_regular.otf"

posx=65
posy=725
pointSize=40
textColor1="#ff7900"	#colorlist: showrgb
textColor2="white"




#######################################
########## GET PLAYER COUNTS ##########
#######################################
uptime=$(awk '{printf "%.2f\n",$1/86400}' /proc/uptime)

#################
### Minecraft ###
#################
    echo "=> obtaining minecraft player count..."
    vanilla=$(netstat -tn | grep -i 25565 | grep ESTABLISHED | wc -l)
    build=$(netstat -tn | grep -i 1234 | grep ESTABLISHED | wc -l)
    wasteland=$(netstat -tn | grep -i 2222 | grep ESTABLISHED | wc -l)
    #Minecraft=$(($vanilla+$wasteland)) #simple version
    
    #TODO: this needs rework?
    #smooth count (prevent rare false detection)
    last=$(<tmp/minecraftlog)
    #echo "last: $last"
    if [ $(($vanilla+$wasteland+$build)) -gt 0 ]; then
    	if [ "$last" == "1" ]; then
    		Minecraft=$(($vanilla+$wasteland+$build))
    	else
    		echo "note: minecraft: $(($vanilla+$wasteland+$build)) aber vorher 0 =>ignorieren"
    		echo "1" > tmp/minecraftlog
    		Minecraft=0
    	fi
    else
    	echo "0" > tmp/minecraftlog
    	Minecraft=0
    fi

	

#################
### Teeworlds ###
#################
echo "=> obtaining teeworlds player count..."
telnet_teeworlds_zcatch () {
	expect << EOF
	spawn telnet -e q raidworld.net 6431
	#expect -re ".*>"
	sleep 0.1
	send "jiawkose\r"
	sleep 0.1
	send "status\r"
	#send "status\r"
	#send "status\r"
	sleep 0.2
	send "q\r" 
	expect -re ".*>"
EOF
}
telnet_teeworlds_vanilla () {
	expect << EOF
	spawn telnet -e q raidworld.net 6432
	#expect -re ".*>"
	sleep 0.1
	send "jiawkose\r"
	sleep 0.1
	send "status\r"
	#send "status\r"
	#send "status\r"
	sleep 0.2
	send "q\r" 
	expect -re ".*>"
EOF
}
tw_zcatch="$(telnet_teeworlds_zcatch | sed 's/^..//' | grep -o 'rver]: id=' | wc -l)"
tw_vanilla="$(telnet_teeworlds_vanilla | sed 's/^..//' | grep -o 'rver]: id=' | wc -l)"
Teeworlds=$(($tw_zcatch+$tw_vanilla))



#################
## Urbanterror ##
#################
    # echo "=> obtaining urbanterror player count..."
    # output="$(lynx -dump -nolist http://www.Urbanterror.info/servers/91.250.87.150:27960/ | grep Slots | cut -c 18-19)"
    # Urbanterror="${output// /}"
    # Urbanterror=0



##################
### 7daystodie ###
##################
    # echo "=> obtaining 7days-to-die player count..."
    # output="$(lynx -dump -nolist https://7daystodie-servers.com/server/60948/ | grep Players | cut -c 21-22)"
    # daystodie="${output// /}"
    # daystodie=0



################
### Factorio ###
################
    # echo "=> obtaining factorio player count..."
    # disconnected="$(grep -o "Disconnect notification" /home/factorio/factorio/factorio-current.log | wc -l)"
    # connected="$(grep -o "JoinGame" /home/factorio/factorio/factorio-current.log | wc -l)"
    # #echo "Factorio-disconnected: $disconnected"
    # #echo "Factorio-connected: $connected"
    # if [ $(($connected - $disconnected)) -gt 0 ]; then
    # 	Factorio=$(($connected - $disconnected))
    # else
    # 	Factorio=0
    # fi




##########################
#### Manipulate count ####
##########################
#Force player count for testing
#Minecraft=1
#Minecraft=$((Minecraft+0))
#Teeworlds=20
#Urbanterror=1
#daystodie=1
#Factorio=0





#Function that generates commands for creating the following text, while supporting 2 different colors:
#"GAME-NAME(parameter-name):" "COUNT(parameter-value)" "player/players" 
#The necessary convert options are appended to the cmd array for later execution with convert
GameToTextCmd () {
    #command for "GAME-NAME":
    cmd+=(-font $fontPath -pointsize $pointSize -fill $textColor1 label:"${1}: " )

    if [ ${!1} -gt 1 ]; then
        #command for "COUNT + 'playerS'"
        cmd+=(-font $fontPath   -pointsize $pointSize  -fill $textColor2 label:"${!1} Players ")
    else
        #command for "COUNT + 'player'"
        cmd+=(-font $fontPath   -pointsize $pointSize  -fill $textColor2 label:"${!1} Player ")
    fi
}




########################################
##### Commands for text generation #####
########################################
#Generate commands for each game and add spacer between games when necessary:
firstgame=1
text="null"
for game in Minecraft Teeworlds Urbanterror daystodie Factorio #list of games
do
	#echo "$game: ${!game}"
	if [[ ${!game} -gt 0 ]]; then
		if [ $firstgame -eq 1 ]; then
			GameToTextCmd $game
			firstgame=0
		else    # add spacer	
            cmd+=(-font $fontPath   -pointsize $pointSize  -fill $textColor1 label:"// ")
			GameToTextCmd $game
		fi
	fi
done




###########################
##### Generate Banner #####
###########################
if [ -n "$cmd" ]; then #cmd array not empty -> generating banner
    echo "[info] some parameters were generated -> creating banner"
    #echo -e "DEBUG: command parameters: \n"${cmd[@]}""
    
    #generate image with text according to generated commands
    echo -e "=> generating text image..."
    convert -background none "${cmd[@]}" +append   tmp/text.png
    
    #merge text image with background
    echo -e "=> merging background image with text..."
    convert $inputPath tmp/text.png -geometry +$posx+$posy -composite $outputPath
    
else #no commands available
    #copy default/empty image
    echo "[info] no text to show (no players?) -> copying default image"
    cp $inputEmpty $outputPath
    sleep 1
fi

#fix permissions for webserver to have access
chmod 666 $outputPath
echo -e "done - $(date)\n"
