#!/usr/bin/env bash
set -euo pipefail

SERVER_NAME="${1:-play.agrariangame.com}"
GAME_PORT="${AGRARIAN_GAME_PORT:-7777}"
INSTALL_DIR="${AGRARIAN_INSTALL_DIR:-/opt/agrarian/server}"
SERVICE_USER="${AGRARIAN_SERVICE_USER:-agrarian}"
MAP_NAME="${AGRARIAN_MAP_NAME:-L_GroundZeroTerrain_Test?listen}"
SERVER_BINARY="${AGRARIAN_SERVER_BINARY:-AgrarianGameServer}"

log() {
  printf '[agrarian-game-server] %s\n' "$*"
}

if [[ "${EUID}" -ne 0 ]]; then
  printf 'Run as root or with sudo.\n' >&2
  exit 1
fi

log "Preparing Ubuntu host for ${SERVER_NAME} on udp/${GAME_PORT}."

export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y ca-certificates curl rsync tar unzip ufw

if ! id "${SERVICE_USER}" >/dev/null 2>&1; then
  useradd --system --home-dir "${INSTALL_DIR}" --create-home --shell /usr/sbin/nologin "${SERVICE_USER}"
fi

install -d -o "${SERVICE_USER}" -g "${SERVICE_USER}" "${INSTALL_DIR}"
install -d -o "${SERVICE_USER}" -g "${SERVICE_USER}" /var/log/agrarian

cat >/etc/systemd/system/agrarian-game-server.service <<UNIT
[Unit]
Description=Agrarian Unreal dedicated gameplay server
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=${SERVICE_USER}
Group=${SERVICE_USER}
WorkingDirectory=${INSTALL_DIR}
ExecStart=${INSTALL_DIR}/${SERVER_BINARY} ${MAP_NAME} -log -port=${GAME_PORT}
Restart=on-failure
RestartSec=10
LimitNOFILE=1048576
StandardOutput=append:/var/log/agrarian/game-server.log
StandardError=append:/var/log/agrarian/game-server.log

[Install]
WantedBy=multi-user.target
UNIT

systemctl daemon-reload
systemctl enable agrarian-game-server.service

if command -v ufw >/dev/null 2>&1; then
  ufw allow "${GAME_PORT}/udp" comment "Agrarian gameplay server"
fi

cat >"${INSTALL_DIR}/DEPLOY_README.txt" <<README
Agrarian gameplay server host prepared for ${SERVER_NAME}.

Copy the Linux dedicated server package contents into:
${INSTALL_DIR}

Expected binary:
${INSTALL_DIR}/${SERVER_BINARY}

Start or restart:
sudo systemctl restart agrarian-game-server

Logs:
sudo journalctl -u agrarian-game-server -f
tail -f /var/log/agrarian/game-server.log

Network:
- Point ${SERVER_NAME} DNS A/AAAA record at this VM.
- Open udp/${GAME_PORT} to the Internet or tester VPN.
- Keep SSH limited to trusted admin IPs.
README

chown "${SERVICE_USER}:${SERVICE_USER}" "${INSTALL_DIR}/DEPLOY_README.txt"

log "Host bootstrap complete."
log "Point DNS ${SERVER_NAME} at this VM and open udp/${GAME_PORT}."
log "Copy the packaged server into ${INSTALL_DIR}, then run: systemctl restart agrarian-game-server"
