#!/bin/bash
# panel-native Palworld entrypoint.
set -euo pipefail
log() { printf '[panel-palworld] %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 \
       SERVER_NAME="${SERVER_NAME:-panel Palworld}" \
       SERVER_DESCRIPTION="${SERVER_DESCRIPTION:-A Palworld server}" \
       MAX_PLAYERS="${MAX_PLAYERS:-32}" \
       RCON_PASSWORD="${RCON_PASSWORD:-panel_rcon}" \
       GAME_PORT="${GAME_PORT:-8211}" \
       QUERY_PORT="${QUERY_PORT:-27015}" \
       RCON_PORT="${RCON_PORT:-25575}" \
       /entrypoint.sh "$@"
fi

GAME_DIR=/game
SAVE_DIR=/game-saves
PAL_SH="${GAME_DIR}/PalServer.sh"
SETTINGS_DIR="${GAME_DIR}/Pal/Saved/Config/LinuxServer"
SETTINGS="${SETTINGS_DIR}/PalWorldSettings.ini"
DEFAULT_SETTINGS="${GAME_DIR}/DefaultPalWorldSettings.ini"

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

# Seed PalWorldSettings.ini on first boot from the shipped default, then
# patch RCON + server name/description/max-players into it. Palworld
# ignores these keys on re-save unless they live in PalWorldSettings.ini
# under [/Script/Pal.PalGameWorldSettings].
mkdir -p "${SETTINGS_DIR}"
if [[ ! -s "${SETTINGS}" && -s "${DEFAULT_SETTINGS}" ]]; then
  log "seeding ${SETTINGS} from shipped default"
  cp -f "${DEFAULT_SETTINGS}" "${SETTINGS}"
fi

# Patch the single OptionSettings=(…) tuple each boot so panel-managed
# values (RCON auth, server identity) track env vars. Uses | as sed
# delimiter since the tuple contains slashes.
if [[ -s "${SETTINGS}" ]]; then
  log "patching ${SETTINGS} (RCON + identity + ports)"
  sed -i -E \
    -e "s|RCONEnabled=(True\|False)|RCONEnabled=True|" \
    -e "s|RCONPort=[0-9]+|RCONPort=${RCON_PORT}|" \
    -e "s|PublicPort=[0-9]+|PublicPort=${GAME_PORT}|" \
    -e "s|AdminPassword=\"[^\"]*\"|AdminPassword=\"${RCON_PASSWORD}\"|" \
    -e "s|ServerPlayerMaxNum=[0-9]+|ServerPlayerMaxNum=${MAX_PLAYERS}|" \
    -e "s|ServerName=\"[^\"]*\"|ServerName=\"${SERVER_NAME}\"|" \
    -e "s|ServerDescription=\"[^\"]*\"|ServerDescription=\"${SERVER_DESCRIPTION}\"|" \
    "${SETTINGS}"
fi

# Redirect Pal saves into the save volume so SteamCMD validate can't clobber.
mkdir -p "${SAVE_DIR}/Pal"
if [[ -d "${GAME_DIR}/Pal/Saved" && ! -L "${GAME_DIR}/Pal/Saved" ]]; then
  # Migrate any existing shipped saves once, then symlink.
  if [[ ! -d "${SAVE_DIR}/Pal/Saved" ]]; then
    mv "${GAME_DIR}/Pal/Saved" "${SAVE_DIR}/Pal/Saved"
  else
    rm -rf "${GAME_DIR}/Pal/Saved"
  fi
fi
mkdir -p "${SAVE_DIR}/Pal/Saved"
ln -sfn "${SAVE_DIR}/Pal/Saved" "${GAME_DIR}/Pal/Saved"

cd "${GAME_DIR}"
log "starting Palworld dedicated server"
log "  name:        ${SERVER_NAME}"
log "  max_players: ${MAX_PLAYERS}"
log "  game port:   ${GAME_PORT}/udp"
log "  query port:  ${QUERY_PORT}/udp"
log "  rcon port:   ${RCON_PORT}/tcp"

exec stdbuf -oL -eL "${PAL_SH}" \
    -port="${GAME_PORT}" \
    -queryport="${QUERY_PORT}" \
    -players="${MAX_PLAYERS}" \
    -useperfthreads \
    -NoAsyncLoadingThread \
    -UseMultithreadForDS \
    "-servername=${SERVER_NAME}" \
    "-adminpassword=${RCON_PASSWORD}" \
    -RconEnabled=True \
    -RconPort="${RCON_PORT}" \
    "-ServerDescription=${SERVER_DESCRIPTION}"
