#!/usr/bin/env bash
# Production process entrypoint for systemd.
# Always updates the tree before starting Node so crash/power-loss recovery
# can pick up a fix from origin (intentional — do not skip pull on crash).
set -euo pipefail

REPO="${QUESTWARD_REPO:-${TILE_MMO_REPO:-$(cd "$(dirname "$0")/.." && pwd)}}"
BRANCH="${QUESTWARD_GIT_BRANCH:-${TILE_MMO_GIT_BRANCH:-master}}"
cd "$REPO"

echo "[deploy] Working tree: $REPO (branch $BRANCH)"
git fetch origin "$BRANCH"
git reset --hard "origin/$BRANCH"
git clean -fd
git pull --ff-only origin "$BRANCH" || true

DEPLOY_DIR="$(cd "$(dirname "$0")" && pwd)"
chmod +x "$DEPLOY_DIR/start-server.sh" "$DEPLOY_DIR/install-service.sh" "$DEPLOY_DIR/update-if-requested.mjs" 2>/dev/null || true

echo "[deploy] npm install…"
npm install --omit=dev

echo "[deploy] Submodules…"
git submodule update --init --recursive

echo "[deploy] Build client framework…"
npm run build:client

if [[ ! -f client/frameworkv3/js/framework.js ]]; then
	echo "[deploy] ERROR: client/frameworkv3/js/framework.js missing after build." >&2
	exit 1
fi

echo "[deploy] Starting server…"
exec node --experimental-sqlite server/src/index.js
