#!/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="${TILE_MMO_REPO:-$(cd "$(dirname "$0")/.." && pwd)}"
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

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

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