#!/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

# Skip npm install when package manifests are unchanged since the last successful install.
# Stamp lives under node_modules/ (gitignored) so it survives hard-reset/pull.
NPM_STAMP="node_modules/.questward-npm-stamp"
npm_manifest_hash ()
{
	# Prefer sha256sum; fall back to shasum (macOS) / openssl.
	if command -v sha256sum >/dev/null 2>&1
	then
		cat package.json package-lock.json | sha256sum | awk '{ print $1 }'
	elif command -v shasum >/dev/null 2>&1
	then
		cat package.json package-lock.json | shasum -a 256 | awk '{ print $1 }'
	else
		cat package.json package-lock.json | openssl dgst -sha256 | awk '{ print $NF }'
	fi
}

WANT_HASH="$(npm_manifest_hash)"
HAVE_HASH=""
if [[ -f "$NPM_STAMP" ]]
then
	HAVE_HASH="$(tr -d '[:space:]' < "$NPM_STAMP" || true)"
fi

if [[ -d node_modules && -n "$HAVE_HASH" && "$HAVE_HASH" == "$WANT_HASH" ]]
then
	echo "[deploy] npm install skipped (package.json / package-lock.json unchanged)"
else
	echo "[deploy] npm install…"
	npm install --omit=dev
	mkdir -p node_modules
	printf '%s\n' "$WANT_HASH" > "$NPM_STAMP"
fi

echo "[deploy] Submodules…"
git submodule sync --recursive
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
