#!/bin/bash

echo "--- Whitelist-Service running ---"

while getopts "h:p:s:i:d:" flag
do
    case "${flag}" in
        h) rcon_host=${OPTARG};;
        p) rcon_port=${OPTARG};;
        s) rcon_pass=${OPTARG};;
        i) check_interval=${OPTARG};;
        d) debug=${OPTARG};;
    esac
done

log()
{
 echo "$1" >> /home/container/whitelist.log
}

# RCON
RCON="/home/container/rcon-0.10.3-amd64_linux/rcon -a $rcon_host:$rcon_port -p $rcon_pass"

while true
do
    # set helper
    KICK="0"

    # DATE FOR LOG
    DATE=`date +%d.%m.%y-%H:%M:%S`
    WHITELISTARRAY=()

    # BUILD ARRAY WITH ALLOWED IDs
    while IFS= read -r line
    do
        if [[ $line != \#* && $line != "" ]]
        then
            WHITELISTARRAY+=("$line")
        fi
    done < <(cat /home/container/whitelist.conf)


    # QUERY THE SERVER AND KICK IF NEEDED
    while IFS= read -r line
    do
        if [ "$line" != "name,playeruid,steamid" ]
        then
            STEAMNAME=$(echo $line | cut -d ',' -f 1)
            PLAYERUID=$(echo $line | cut -d ',' -f 2)
            STEAMID=$(echo $line | cut -d ',' -f 3)

            if [[ ! ${WHITELISTARRAY[@]} =~ $STEAMID ]]
            then
                echo "[$DATE] Player $STEAMNAME with SteamID $STEAMID and PlayerUID $PLAYERUID not allowed list. Kick will initiated."
                log "[$DATE] Player $STEAMNAME with SteamID $STEAMID and PlayerUID $PLAYERUID not allowed list. Kick will initiated."
                if [ "$debug" == "0" ]
                then
                    $RCON "KickPlayer $PLAYERUID"
                fi
                KICK="1"
            fi
        fi
    done < <($RCON ShowPlayers 2>/dev/null)

    # print shit just in case, that there was an output generated
    if [[ $KICK == "1" ]]
    then
        echo "----------------------------------------------------------------------"
    fi

    # go sleep
    sleep $check_interval
done
