#!/bin/bash
# panel-native Terraria entrypoint.
set -euo pipefail
log() { printf '[panel-terraria] %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 \
       WORLD_NAME="${WORLD_NAME:-DedicatedWorld}" \
       WORLD_SIZE="${WORLD_SIZE:-2}" \
       MAX_PLAYERS="${MAX_PLAYERS:-8}" \
       SERVER_PASSWORD="${SERVER_PASSWORD:-}" \
       GAME_PORT="${GAME_PORT:-7777}" \
       /entrypoint.sh "$@"
fi

GAME_DIR=/game
SAVE_DIR=/game-saves

# The panel's direct update provider drops the raw zip at
# /game-saves/terraria-server.zip (it does not extract archives).
# Unpack it into /game on boot, then delete the zip.
ZIP="${SAVE_DIR}/terraria-server.zip"
if [[ -s "${ZIP}" ]]; then
  log "extracting $(basename "${ZIP}") into ${GAME_DIR}"
  unzip -o -q "${ZIP}" -d "${GAME_DIR}"
  rm -f "${ZIP}"
fi

# Terraria's zip extracts into /game/<version>/{Linux,Mac,Windows}. Find
# the Linux dir regardless of version folder name.
LINUX_DIR=$(find "${GAME_DIR}" -maxdepth 3 -type d -name Linux 2>/dev/null | head -n1 || true)
if [[ -z "${LINUX_DIR}" ]]; then
  log "ERROR: Terraria Linux server binary not found under /game."
  log "       Run 'Update' in the panel to download Terraria headless server."
  exit 78
fi
EXE="${LINUX_DIR}/TerrariaServer.bin.x86_64"
[[ -x "${EXE}" ]] || chmod +x "${EXE}" 2>/dev/null || true

# Terraria reads serverconfig.txt if -config is passed. Seed a minimal one
# with our env vars so the server starts without interactive prompts.
CONFIG="${SAVE_DIR}/serverconfig.txt"
if [[ ! -s "${CONFIG}" ]]; then
  log "seeding ${CONFIG}"
  {
    echo "world=${SAVE_DIR}/Worlds/${WORLD_NAME}.wld"
    echo "worldname=${WORLD_NAME}"
    echo "autocreate=${WORLD_SIZE}"
    echo "maxplayers=${MAX_PLAYERS}"
    echo "port=${GAME_PORT:-7777}"
    echo "motd=Running on panel"
    echo "difficulty=1"
    [[ -n "${SERVER_PASSWORD}" ]] && echo "password=${SERVER_PASSWORD}" || true
  } > "${CONFIG}"
fi
mkdir -p "${SAVE_DIR}/Worlds"

cd "${LINUX_DIR}"
log "starting Terraria dedicated server"
log "  world:   ${WORLD_NAME} (size ${WORLD_SIZE})"
log "  config:  ${CONFIG}"
log "  port:    ${GAME_PORT:-7777}"

# -port on the command line overrides serverconfig.txt, so a panel port
# change takes effect even when a stale config was seeded on a prior boot.
exec stdbuf -oL -eL "${EXE}" -config "${CONFIG}" -port "${GAME_PORT:-7777}"
