#!/bin/bash
# panel-native Core Keeper entrypoint.
set -euo pipefail
log() { printf '[panel-core-keeper] %s\n' "$*"; }

if [[ "$(id -u)" = "0" ]]; then
  chown -R panel:panel /game /game-saves /home/panel 2>/dev/null || true
  rm -f /tmp/.X99-lock /tmp/.X11-unix/X99 2>/dev/null || true
  mkdir -p /tmp/.X11-unix && chmod 1777 /tmp/.X11-unix && chown root:root /tmp/.X11-unix 2>/dev/null || true
  exec setpriv --reuid=panel --regid=panel --clear-groups \
       --inh-caps=-all --bounding-set=-all \
       env HOME=/game-saves DISPLAY=:99 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \
       GAME_ID="${GAME_ID:-}" \
       WORLD_NAME="${WORLD_NAME:-panel}" \
       WORLD_MODE="${WORLD_MODE:-0}" \
       MAX_PLAYERS="${MAX_PLAYERS:-10}" \
       GAME_PORT="${GAME_PORT:-27015}" \
       /entrypoint.sh "$@"
fi

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

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

log "starting Xvfb on :99"
Xvfb :99 -screen 0 1024x768x24 -nolisten tcp &
XVFB_PID=$!
sleep 1

# Core Keeper writes saves under $HOME/.config/unity3d/Pugstorm/Core Keeper.
# HOME is /game-saves so these persist.
mkdir -p "${SAVE_DIR}/.config/unity3d/Pugstorm/Core Keeper"

trap 'log "SIGTERM"; kill "${XVFB_PID}" 2>/dev/null || true; exit 0' TERM INT

cd "${GAME_DIR}"
log "starting Core Keeper dedicated server"
log "  world: ${WORLD_NAME} (mode ${WORLD_MODE}, max ${MAX_PLAYERS}), port ${GAME_PORT}"

# Steamworks needs the bundled linux64/steamclient.so and the GAME app id
# (1621690, not the dedicated-server app 1963720) — per AMP's
# core-keeper.kvp EnvironmentVariables.
export LD_LIBRARY_PATH="${GAME_DIR}/linux64${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
export SteamAppId=1621690

# -port makes the server open a direct UDP socket on the panel-allocated
# port (instead of Steam-relay-only). -datapath keeps worlds in the
# persistent save volume.
ARGS=(-batchmode -logfile -
      -port "${GAME_PORT}"
      -datapath "${SAVE_DIR}/DedicatedServer"
      -worldname "${WORLD_NAME}" -worldmode "${WORLD_MODE}"
      -maxplayers "${MAX_PLAYERS}")
if [[ -n "${GAME_ID}" ]]; then
  ARGS+=(-gameid "${GAME_ID}")
fi
mkdir -p "${SAVE_DIR}/DedicatedServer"

exec stdbuf -oL -eL "${EXE}" "${ARGS[@]}"
