#!/bin/bash
# panel-native Enshrouded entrypoint (Windows server under Wine + Xvfb).
set -euo pipefail
log() { printf '[panel-enshrouded] %s\n' "$*"; }

# ----- stage 1: root-only bootstrap, then drop to panel (Wine refuses root) -----
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 Enshrouded}" \
           SERVER_PASSWORD="${SERVER_PASSWORD:-letmein}" \
           MAX_PLAYERS="${MAX_PLAYERS:-16}" \
           QUERY_PORT="${QUERY_PORT:-15637}" \
       /entrypoint.sh "$@"
fi

GAME_DIR=/game
SAVE_DIR=/game-saves
EXE="${GAME_DIR}/enshrouded_server.exe"
CONFIG="${SAVE_DIR}/enshrouded_server.json"

if [[ ! -f "${EXE}" ]]; then
  log "ERROR: ${EXE} not found. Run 'Update' in the panel — that launches a"
  log "       SteamCMD sidecar which installs the Windows build (app 2278520,"
  log "       +@sSteamCmdForcePlatformType windows) into this volume."
  exit 78   # EX_CONFIG
fi

mkdir -p "${SAVE_DIR}/savegame" "${SAVE_DIR}/logs"

# Seed enshrouded_server.json on first boot. The Steam depot does not ship a
# config (the server generates one), so we write our own — deterministic, and
# the env->json patching below always has keys to patch. Paths are relative
# to the exe's directory; we symlink savegame/ + logs/ into the save volume.
if [[ ! -s "${CONFIG}" ]]; then
  log "seeding default ${CONFIG}"
  cat > "${CONFIG}" <<'EOF'
{
  "name": "panel Enshrouded",
  "password": "",
  "saveDirectory": "./savegame",
  "logDirectory": "./logs",
  "ip": "0.0.0.0",
  "queryPort": 15637,
  "slotCount": 16
}
EOF
fi

# Basic env -> json patching. Enshrouded config is small + flat so a few
# seds are fine without pulling jq in.
sed -i "s|\"name\":\\s*\"[^\"]*\"|\"name\": \"${SERVER_NAME}\"|" "${CONFIG}"
sed -i "s|\"password\":\\s*\"[^\"]*\"|\"password\": \"${SERVER_PASSWORD}\"|" "${CONFIG}"
sed -i "s|\"slotCount\":\\s*[0-9]*|\"slotCount\": ${MAX_PLAYERS}|" "${CONFIG}"
# Panel-allocated port. Modern Enshrouded has a single UDP port (queryPort);
# gamePort no longer exists in the config schema.
sed -i "s|\"queryPort\":\\s*[0-9]*|\"queryPort\": ${QUERY_PORT}|" "${CONFIG}"

# Config + save/log dirs live in the save volume; symlink them next to the
# exe (the server resolves config + relative paths from its own directory).
ln -sf "${CONFIG}" "${GAME_DIR}/enshrouded_server.json"
for d in savegame logs; do
  if [[ -d "${GAME_DIR}/${d}" && ! -L "${GAME_DIR}/${d}" ]]; then rm -rf "${GAME_DIR}/${d}"; fi
  ln -sfn "${SAVE_DIR}/${d}" "${GAME_DIR}/${d}"
done

# --- Wine prefix bootstrap / repair (image pre-warms it; repair if broken) ---
if [[ ! -f "${WINEPREFIX}/system.reg" || ! -f "${WINEPREFIX}/drive_c/windows/system32/kernel32.dll" ]]; then
  log "initializing Wine prefix at ${WINEPREFIX}"
  rm -rf "${WINEPREFIX}"
  xvfb-run -a env WINEDLLOVERRIDES="mscoree=;mshtml=" wineboot --init 2>&1 | sed 's/^/  /' || true
  wineserver -w || true
fi

cd "${GAME_DIR}"
log "starting Enshrouded dedicated server (Wine)"
log "  name:   ${SERVER_NAME}"
log "  slots:  ${MAX_PLAYERS}"
log "  port:   ${QUERY_PORT}/udp"

# The server writes its real log to ./logs/enshrouded_server.log; mirror it
# to stdout so the panel's log follower + ready_pattern see it even if the
# Wine console output is sparse. tail -F copes with the file not existing yet.
tail -n +1 -F "${SAVE_DIR}/logs/enshrouded_server.log" 2>/dev/null &
TAIL_PID=$!

trap 'log "SIGTERM received; stopping server"; wineserver -k 2>/dev/null || true; kill "${TAIL_PID:-}" 2>/dev/null || true; exit 0' TERM INT

exec stdbuf -oL -eL xvfb-run -a --server-args="-screen 0 1024x768x24" \
    wine "${EXE}"
