#!/bin/bash
# panel-native Satisfactory entrypoint.
set -euo pipefail
log() { printf '[panel-satisfactory] %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 \
       GAME_PORT="${GAME_PORT:-7777}" RELIABLE_PORT="${RELIABLE_PORT:-8888}" \
       /entrypoint.sh "$@"
fi

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

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

# Satisfactory writes SaveGames / Engine configs to
# $HOME/.config/Epic/FactoryGame. HOME is /game-saves → saves land in the
# save volume without further fiddling.
mkdir -p "${SAVE_DIR}/.config/Epic/FactoryGame/Saved/SaveGames"

GAME_PORT="${GAME_PORT:-7777}"
RELIABLE_PORT="${RELIABLE_PORT:-8888}"

cd "${GAME_DIR}"
log "starting Satisfactory dedicated server (game=${GAME_PORT}/udp+tcp reliable=${RELIABLE_PORT}/tcp)"

# -Port drives both the UDP game socket and the HTTPS API listener (they
# share the number). -ReliablePort is the TCP reliability channel (1.0+).
# -stdout -FullStdOutLogOutput route UE logs to stdout for `docker logs`.
exec stdbuf -oL -eL "${START_SH}" \
    -Port="${GAME_PORT}" \
    -ReliablePort="${RELIABLE_PORT}" \
    -multihome=0.0.0.0 \
    -stdout -FullStdOutLogOutput \
    -unattended
