#!/bin/bash

# shellcheck source=start-utils
. "$(dirname "$0")/start-utils"

: "${SERVER_PORT:=25565}"
: "${ENABLE_AUTOPAUSE:=false}"
: "${AUTOPAUSE_TIMEOUT_EST:=3600}"
: "${AUTOPAUSE_TIMEOUT_KN:=120}"
: "${AUTOPAUSE_TIMEOUT_INIT:=600}"
: "${AUTOPAUSE_PERIOD:=10}"
: "${AUTOPAUSE_KNOCK_INTERFACE:=eth0}"
: "${DEBUG_AUTOPAUSE:=false}"
export SERVER_PORT
export ENABLE_AUTOPAUSE
export AUTOPAUSE_TIMEOUT_EST
export AUTOPAUSE_TIMEOUT_KN
export AUTOPAUSE_TIMEOUT_INIT
export AUTOPAUSE_PERIOD
export AUTOPAUSE_KNOCK_INTERFACE
export DEBUG_AUTOPAUSE

log "Autopause functionality enabled"

isDebugging && set -x

cp /image/knockd-config.cfg /data/.knockd.cfg

function updatePort() {
  regseq="^\s*sequence\s*=\s*$1\s*$"
  linenum=$(grep -nm${2} sequence /data/.knockd.cfg | cut -d : -f 1 | tail -n1)
  if ! [[ $(awk "NR==$linenum" /data/.knockd.cfg) =~ $regseq ]]; then
    sed -i "${linenum}s/sequence.*/sequence = $1/" /data/.knockd.cfg
    log "Updated $3 port in knockd config"
  fi
}

# update server port to listen to
updatePort $SERVER_PORT 1 "server"

# update rcon port to listen to
updatePort $RCON_PORT 2 "rcon"

isNumericElseSetToDefault "AUTOPAUSE_PERIOD" 10
checkIfNotZeroElseSetToDefault "AUTOPAUSE_PERIOD" 10
isNumericElseSetToDefault "AUTOPAUSE_TIMEOUT_KN" 120
isNumericElseSetToDefault "AUTOPAUSE_TIMEOUT_EST" 3600
isNumericElseSetToDefault "AUTOPAUSE_TIMEOUT_INIT" 600

if [[ "$AUTOPAUSE_KNOCK_INTERFACE" == "lo" ]] ; then
  logWarning "AUTOPAUSE_KNOCK_INTERFACE is set to the local loopback interface."
  logWarning "         This is not advisable, as incoming connections are likely not picked up there."
  logWarning "         Continuing with this setting."
fi

# seq_cooldown cannot be larger than AUTOPAUSE_TIMEOUT_KN, otherwise the server may
# become paused while knockd is still ignoring packets, preventing players from joining.
let COOLDOWN=$AUTOPAUSE_TIMEOUT_KN/2
sed -i "s/\(seq_cooldown *= *\).*/\1$COOLDOWN/" /data/.knockd.cfg

if isDebugging; then
  echo "Autopause configuration: ======================================"
  cat /data/.knockd.cfg
  echo "==============================================================="
fi

"$(dirname "$0")/auto/autopause-daemon.sh" &
