#!/bin/bash
# panel-native Barotrauma entrypoint.
set -euo pipefail
log() { printf '[panel-barotrauma] %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=/game-saves PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \
       /entrypoint.sh "$@"
fi

GAME_DIR=/game
SAVE_DIR=/game-saves
EXE="${GAME_DIR}/DedicatedServer"

if [[ ! -f "${EXE}" ]]; then
  log "ERROR: ${EXE} not found. Run 'Update' in the panel to install Barotrauma via SteamCMD."
  exit 78
fi
[[ -x "${EXE}" ]] || chmod +x "${EXE}"

# ---- panel port wiring ----------------------------------------------------
# Barotrauma has no CLI port args; ports live as attributes on the root
# <serversettings> element. Seed a minimal file on first boot, then patch
# port=/queryport= from the panel-allocated env on EVERY boot so a panel
# port change is durable (the server rewrites the full file on exit).
GAME_PORT="${GAME_PORT:-27015}"
QUERY_PORT="${QUERY_PORT:-27016}"
SETTINGS="${SAVE_DIR}/serversettings.xml"
if [[ ! -f "${SETTINGS}" ]]; then
  log "seeding serversettings.xml (name=${SERVER_NAME:-panel Barotrauma}, port=${GAME_PORT}, queryport=${QUERY_PORT})"
  cat > "${SETTINGS}" <<EOF
<?xml version="1.0" encoding="utf-8"?>
<serversettings name="${SERVER_NAME:-panel Barotrauma}" port="${GAME_PORT}" queryport="${QUERY_PORT}" MaxPlayers="${MAX_PLAYERS:-16}" password="${SERVER_PASSWORD:-}" IsPublic="${IS_PUBLIC:-True}" EnableUPnP="false" />
EOF
else
  sed -i -E "s/\bport=\"[0-9]+\"/port=\"${GAME_PORT}\"/; s/\bqueryport=\"[0-9]+\"/queryport=\"${QUERY_PORT}\"/" "${SETTINGS}"
  log "patched serversettings.xml ports (port=${GAME_PORT}, queryport=${QUERY_PORT})"
fi

# The server resolves config paths relative to the executable dir (/game),
# NOT the CWD — confirmed on first boot ("Could not find file
# '/game/serversettings.xml'"). Symlink the configs onto the save volume so
# they survive reinstalls and are browseable under Saves & Configs.
for f in serversettings.xml clientpermissions.xml; do
  ln -sfn "${SAVE_DIR}/${f}" "${GAME_DIR}/${f}"
done

# Steamworks wants $HOME/.steam/sdk64/steamclient.so. The install ships a
# 64-bit copy at linux64/steamclient.so (the top-level one is 32-bit and
# fails with ELFCLASS32). Without this the server still boots (Lidgren),
# but the A2S query port never answers.
mkdir -p "${HOME}/.steam/sdk64"
ln -sfn "${GAME_DIR}/linux64/steamclient.so" "${HOME}/.steam/sdk64/steamclient.so"

# Barotrauma reads/writes serversettings.xml, clientpermissions.xml, saves/
# from CWD by default. Point CWD at save volume so nothing lives in /game.
cd "${SAVE_DIR}"
log "starting Barotrauma dedicated server"

export LD_LIBRARY_PATH="${GAME_DIR}:${LD_LIBRARY_PATH:-}"
exec stdbuf -oL -eL "${EXE}"
