#!/bin/bash
# panel-native Project Zomboid entrypoint.
set -euo pipefail
log() { printf '[panel-pz] %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}" \
       ADMIN_PASSWORD="${ADMIN_PASSWORD:-changeme}" \
       RCON_PASSWORD="${RCON_PASSWORD:-panel_rcon}" \
       MEMORY="${MEMORY:-4096m}" \
       GAME_PORT="${GAME_PORT:-16261}" \
       GAME_PORT_B="${GAME_PORT_B:-16262}" \
       RCON_PORT="${RCON_PORT:-27015}" \
       /entrypoint.sh "$@"
fi

GAME_DIR=/game
SAVE_DIR=/game-saves
START_SH="${GAME_DIR}/start-server.sh"

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

# PZ writes world data + per-server config under $HOME/Zomboid (Linux) by
# default. HOME is already /game-saves via setpriv; pre-create subdirs.
mkdir -p "${SAVE_DIR}/Zomboid/Server" "${SAVE_DIR}/Zomboid/Saves"

# Per-server config at ~/Zomboid/Server/<SERVER_NAME>.ini. Seed on first
# boot, then ALWAYS enforce the panel-allocated ports + RCON creds so a
# recreate with new ports never leaves stale values in an existing ini.
CFG="${SAVE_DIR}/Zomboid/Server/${SERVER_NAME}.ini"
if [[ ! -s "${CFG}" ]]; then
  log "seeding ${CFG}"
  cat > "${CFG}" <<EOF
PublicName=${SERVER_NAME}
Public=false
MaxPlayers=16
PVP=true
Pause=false
PauseEmpty=true
AutoCreateUserInWhiteList=false
Open=true
ServerWelcomeMessage=Running on panel
UPnP=false
EOF
fi

# set_ini KEY VALUE — replace-or-append into ${CFG}.
set_ini() {
  local key="$1" val="$2"
  if grep -q "^${key}=" "${CFG}"; then
    sed -i "s|^${key}=.*|${key}=${val}|" "${CFG}"
  else
    printf '%s=%s\n' "${key}" "${val}" >> "${CFG}"
  fi
}
set_ini DefaultPort   "${GAME_PORT}"
set_ini UDPPort       "${GAME_PORT_B}"
set_ini RCONPort      "${RCON_PORT}"
set_ini RCONPassword  "${RCON_PASSWORD}"
set_ini UPnP          "false"

# JVM heap: start-server.sh reads vmArgs from ProjectZomboid64.json (the
# MEMORY env is NOT read by the stock script) — patch the -Xmx entry.
PZ_JSON="${GAME_DIR}/ProjectZomboid64.json"
if [[ -f "${PZ_JSON}" ]]; then
  sed -i "s|-Xmx[0-9]*[kmgKMG]\?|-Xmx${MEMORY}|" "${PZ_JSON}" || true
fi

cd "${GAME_DIR}"
log "starting Project Zomboid dedicated server"
log "  servername: ${SERVER_NAME}"
log "  heap:       ${MEMORY}"
log "  ports:      game=${GAME_PORT}/udp direct=${GAME_PORT_B}/udp rcon=${RCON_PORT}/tcp"

# start-server.sh forwards program args to zombie.network.GameServer.
# -port/-udpport mirror the ini keys (AMP passes the same pair).
# -cachedir is REQUIRED: pzexe derives its data dir from the passwd home
# (/home/panel), NOT $HOME — without it the ini/saves silently land inside
# the container layer and the seeded ini above is never read (confirmed:
# 'cachedir set to "/home/panel/Zomboid"' on first smoke boot).
exec stdbuf -oL -eL "${START_SH}" \
  "-cachedir=${SAVE_DIR}/Zomboid" \
  -servername "${SERVER_NAME}" \
  -adminpassword "${ADMIN_PASSWORD}" \
  -port "${GAME_PORT}" \
  -udpport "${GAME_PORT_B}"
