#!/bin/bash
# panel-native V Rising entrypoint (Wine).
#
# CLI flags > JSON in V Rising's override precedence, so we drive every
# operator-facing knob via -flag args from env vars rather than rewriting
# ServerHostSettings.json on each boot. The shipped JSON in StreamingAssets/
# stays untouched; operators who want individual ServerGameSettings.json
# edits can ssh in / use the Files tab and edit the seeded copy in
# /game-saves/Settings — but only if GAME_SETTINGS_PRESET is empty (a
# non-empty preset overrides individual edits silently — Stunlock gotcha).
set -euo pipefail
log() { printf '[panel-v-rising] %s\n' "$*"; }

if [[ "$(id -u)" = "0" ]]; then
  chown -R panel:panel /game /game-saves /home/panel 2>/dev/null || true
  # Hand off to panel user. setpriv preserves env, so all the SERVER_*
  # / GAME_* / RCON_* knobs the panel manifest sets reach the child.
  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 \
       /entrypoint.sh "$@"
fi

GAME_DIR=/game
SAVE_DIR=/game-saves
EXE="${GAME_DIR}/VRisingServer.exe"
SETTINGS_SRC="${GAME_DIR}/VRisingServer_Data/StreamingAssets/Settings"
SETTINGS_DST="${SAVE_DIR}/Settings"

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

# Seed ServerHostSettings.json + ServerGameSettings.json into save volume
# the first time only. After that the operator can edit them by hand for
# settings the panel doesn't expose; CLI flags below still override the
# operator-facing keys (Name, Description, ports, password, max players).
mkdir -p "${SETTINGS_DST}"
if [[ ! -s "${SETTINGS_DST}/ServerHostSettings.json" && -d "${SETTINGS_SRC}" ]]; then
  log "seeding ${SETTINGS_DST} from shipped defaults"
  cp -r "${SETTINGS_SRC}/." "${SETTINGS_DST}/" || true
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

# ---- Env defaults (mirrors module.yaml's env: block) ----
SERVER_NAME="${SERVER_NAME:-panel V Rising}"
SERVER_DESCRIPTION="${SERVER_DESCRIPTION:-}"
SERVER_PASSWORD="${SERVER_PASSWORD:-}"
MAX_PLAYERS="${MAX_PLAYERS:-40}"
MAX_ADMINS="${MAX_ADMINS:-4}"
SAVE_NAME="${SAVE_NAME:-panel}"
LIST_ON_STEAM="${LIST_ON_STEAM:-true}"
LIST_ON_EOS="${LIST_ON_EOS:-true}"
SECURE="${SECURE:-true}"
SERVER_FPS="${SERVER_FPS:-30}"
LOWER_FPS_WHEN_EMPTY="${LOWER_FPS_WHEN_EMPTY:-true}"
GAME_SETTINGS_PRESET="${GAME_SETTINGS_PRESET:-}"
GAME_DIFFICULTY_PRESET="${GAME_DIFFICULTY_PRESET:-}"
GAME_PORT="${GAME_PORT:-9876}"
QUERY_PORT="${QUERY_PORT:-9877}"
RCON_ENABLED="${RCON_ENABLED:-false}"
RCON_PORT="${RCON_PORT:-25575}"
RCON_PASSWORD="${RCON_PASSWORD:-}"

# ---- Build CLI args ----
ARGS=(
  -persistentDataPath  "${SAVE_DIR}"
  -saveName            "${SAVE_NAME}"
  -serverName          "${SERVER_NAME}"
  -gamePort            "${GAME_PORT}"
  -queryPort           "${QUERY_PORT}"
  -maxUsers            "${MAX_PLAYERS}"
  -maxAdmins           "${MAX_ADMINS}"
  -listOnSteam         "${LIST_ON_STEAM}"
  -listOnEOS           "${LIST_ON_EOS}"
  -secure              "${SECURE}"
  -targetFps           "${SERVER_FPS}"
  -lowerFPSWhenEmpty   "${LOWER_FPS_WHEN_EMPTY}"
  -logFile             "-"
  -batchmode -nographics
)
[[ -n "${SERVER_DESCRIPTION}"      ]] && ARGS+=(-description       "${SERVER_DESCRIPTION}")
[[ -n "${SERVER_PASSWORD}"         ]] && ARGS+=(-password          "${SERVER_PASSWORD}")
[[ -n "${GAME_SETTINGS_PRESET}"    ]] && ARGS+=(-preset            "${GAME_SETTINGS_PRESET}")
[[ -n "${GAME_DIFFICULTY_PRESET}"  ]] && ARGS+=(-difficultyPreset  "${GAME_DIFFICULTY_PRESET}")
if [[ "${RCON_ENABLED}" == "true" ]]; then
  ARGS+=(-rconEnabled true -rconPort "${RCON_PORT}" -rconPassword "${RCON_PASSWORD}")
fi

cd "${GAME_DIR}"
log "starting V Rising dedicated server"
log "  name:    ${SERVER_NAME}"
log "  ports:   ${GAME_PORT}/${QUERY_PORT} (game/query)"
log "  slots:   ${MAX_PLAYERS}"
log "  preset:  ${GAME_SETTINGS_PRESET:-(none)}"
log "  rcon:    ${RCON_ENABLED} (port ${RCON_PORT})"

# xvfb-run -a auto-allocates a free display — host has its own Xvfb on
# :99 / :100 / :101, see panel/memory/gotchas.md.
exec stdbuf -oL -eL xvfb-run -a --server-args="-screen 0 1024x768x24" \
    wine "${EXE}" "${ARGS[@]}"
