#!/bin/bash
# panel-native Sons Of The Forest entrypoint (Wine).
set -euo pipefail
log() { printf '[panel-sotf] %s\n' "$*"; }

if [[ "$(id -u)" = "0" ]]; then
  chown -R panel:panel /game /game-saves /home/panel 2>/dev/null || true
  exec setpriv --reuid=panel --regid=panel --clear-groups \
       --inh-caps=-all --bounding-set=-all \
       env HOME=/home/panel WINEPREFIX=/home/panel/.wine WINEDEBUG=-all \
       PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \
       SERVER_NAME="${SERVER_NAME:-panel Sons Of The Forest}" \
       MAX_PLAYERS="${MAX_PLAYERS:-8}" \
       SERVER_PASSWORD="${SERVER_PASSWORD:-}" \
       GAME_PORT="${GAME_PORT:-8766}" \
       QUERY_PORT="${QUERY_PORT:-27016}" \
       BLOBSYNC_PORT="${BLOBSYNC_PORT:-9700}" \
       /entrypoint.sh "$@"
fi

GAME_DIR=/game
SAVE_DIR=/game-saves
EXE="${GAME_DIR}/SonsOfTheForestDS.exe"
# The server looks for dedicatedserver.cfg directly inside -userdatapath.
CONFIG="${SAVE_DIR}/dedicatedserver.cfg"

if [[ ! -f "${EXE}" ]]; then
  log "ERROR: ${EXE} not found. Run 'Update' in the panel to install SOTF (Windows build) via SteamCMD."
  exit 78
fi

# Seed dedicatedserver.cfg (JSON-ish) on first boot from env. On subsequent
# boots, patch the port keys so panel-allocated ports flow into a config
# the operator may have hand-edited (preserves their other tweaks).
mkdir -p "${SAVE_DIR}"
if [[ ! -s "${CONFIG}" ]]; then
  log "seeding ${CONFIG}"
  cat > "${CONFIG}" <<EOF
{
  "IpAddress": "0.0.0.0",
  "ServerName": "${SERVER_NAME}",
  "MaxPlayers": ${MAX_PLAYERS},
  "Password": "${SERVER_PASSWORD}",
  "GamePort": ${GAME_PORT},
  "QueryPort": ${QUERY_PORT},
  "BlobSyncPort": ${BLOBSYNC_PORT},
  "LanOnly": false,
  "SaveSlot": 1,
  "SaveMode": "Continue",
  "GameMode": "Normal",
  "SaveInterval": 600,
  "LogFilesEnabled": false,
  "TimestampLogFilenames": true,
  "TimestampLogEntries": true,
  "SkipNetworkAccessibilityTest": true
}
EOF
else
  log "patching ${CONFIG} (ports from env)"
  # JSON int keys — sed targets `"Key": NNNN` allowing any current value.
  sed -i -E \
    -e "s|(\"GamePort\":[[:space:]]*)[0-9]+|\1${GAME_PORT}|" \
    -e "s|(\"QueryPort\":[[:space:]]*)[0-9]+|\1${QUERY_PORT}|" \
    -e "s|(\"BlobSyncPort\":[[:space:]]*)[0-9]+|\1${BLOBSYNC_PORT}|" \
    "${CONFIG}"
fi

if [[ ! -f "${WINEPREFIX}/system.reg" ]]; then
  log "initializing Wine prefix at ${WINEPREFIX}"
  xvfb-run -a wineboot --init 2>&1 | sed 's/^/  /' || true
  wineserver -w || true
fi

trap 'log "SIGTERM"; wineserver -k 2>/dev/null || true; exit 0' TERM INT

cd "${GAME_DIR}"
log "starting Sons Of The Forest dedicated server"
log "  name:        ${SERVER_NAME}"
log "  game/query:  ${GAME_PORT}/${QUERY_PORT}/udp"
log "  blobsync:    ${BLOBSYNC_PORT}/udp"

# xvfb-run -a auto-allocates a free X display (host has its own Xvfb on
# :99 / :100 / :101 — see panel/memory/gotchas.md).
# Args mirror AMPTemplates sons-of-the-forest.kvp App.CommandLineArgs:
# -dedicatedserver.* CLI overrides beat the cfg, so panel-allocated ports
# always win even if the operator hand-edits dedicatedserver.cfg.
exec stdbuf -oL -eL xvfb-run -a --server-args="-screen 0 1024x768x24" \
    wine "${EXE}" \
    -dedicatedserver.IpAddress "0.0.0.0" \
    -dedicatedserver.GamePort "${GAME_PORT}" \
    -dedicatedserver.QueryPort "${QUERY_PORT}" \
    -dedicatedserver.BlobSyncPort "${BLOBSYNC_PORT}" \
    -userdatapath "${SAVE_DIR}"
