#!/usr/bin/env bash
# SEO Insight — build & (re)deploy on the VPS. Run as the `seoinsight` user from
# /opt/seo-insight. Idempotent: safe for the first install and every update.
#
#   cd /opt/seo-insight && ./deploy/deploy.sh
#
# Steps: pull → install deps → build the Rust wasm + the GSC worker → migrate the
# DB → build Next → restart the systemd services. Stops on the first error.
set -euo pipefail
cd "$(dirname "$0")/.."

# Make bun / cargo / wasm-pack resolvable without relying on the login shell's
# profile — the `seoinsight` system user (adduser --system) has no ~/.profile to
# source ~/.bashrc, so a `bash -lc` run otherwise can't find bun.
export BUN_INSTALL="${BUN_INSTALL:-$HOME/.bun}"
export PATH="$BUN_INSTALL/bin:$HOME/.cargo/bin:$HOME/.local/bin:$PATH"
[ -f "$HOME/.cargo/env" ] && . "$HOME/.cargo/env"

# Load the prod env so `db:migrate` and `next build` (which evaluate the Zod env
# schema at build time) see DATABASE_URL et al. Quoted values (EMAIL_FROM) are
# handled by the shell. The systemd units load the same file at runtime.
if [ -f .env.production ]; then
	set -a
	# shellcheck disable=SC1091
	. ./.env.production
	set +a
fi

# main = PRODUCTION (see the repo's git-flow rules). Deploy ALWAYS tracks main,
# never whatever branch happened to be checked out. Override with DEPLOY_BRANCH=…
# only for a deliberate hotfix off another branch.
DEPLOY_BRANCH="${DEPLOY_BRANCH:-main}"
echo "▸ Fetching origin & forcing '$DEPLOY_BRANCH'…"
git fetch origin "$DEPLOY_BRANCH" --tags --prune
git checkout "$DEPLOY_BRANCH"
# Hard-reset to the remote tip: this box is deploy-only (no local commits), so a
# reset is safe and guarantees the tree exactly matches origin/$DEPLOY_BRANCH even
# if the local branch ever diverged. Generated/gitignored files (the import-core
# wasm) are untouched by reset.
git reset --hard "origin/$DEPLOY_BRANCH"

echo "▸ Building the import-core wasm (gitignored 'file:' dep — must exist BEFORE
       bun install resolves it). Call wasm-pack directly so bun never sees the
       missing dir…"
wasm-pack build crates/import-core --release --target nodejs \
  --out-dir ../../src/lib/backlink/import-core --out-name import_core
wasm-pack build crates/semantic-core --release --target nodejs \
  --out-dir ../../src/lib/semantic/semantic-core --out-name semantic_core

echo "▸ Installing JS deps (root + analytics service)…"
bun install
( cd services/analytics && bun install )

echo "▸ Building the GSC worker (release binary)…"
cargo build --release -p gsc-worker

echo "▸ Applying DB migrations…"
bun run db:migrate

echo "▸ Building Next…"
bun run build

# Les unités systemd du dépôt ne sont PAS installées par ce script : y écrire
# demanderait de donner à `seoinsight` le droit d'écrire dans /etc/systemd/system
# et de recharger le démon, c'est-à-dire root (toute unité déposée là s'exécute
# avec les pleins droits). On se contente donc de DÉTECTER l'écart et de le dire
# — la copie est une opération root explicite, deploy/sync-systemd.sh.
#
# Cette détection tourne sans privilège : les unités installées sont lisibles.
SYSTEMD_DRIFT=()
for src in deploy/systemd/*.service deploy/systemd/*.timer; do
	[ -e "$src" ] || continue
	name="$(basename "$src")"
	dest="/etc/systemd/system/$name"
	if [ ! -f "$dest" ]; then
		SYSTEMD_DRIFT+=("$name (absente du système)")
	elif ! cmp -s "$src" "$dest"; then
		SYSTEMD_DRIFT+=("$name (diffère de la version installée)")
	fi
done

echo "▸ Restarting services…"
# Restart each individually so it matches the NOPASSWD sudoers entries. The
# gsc-worker is a one-shot driven by seo-insight-gsc-worker.timer — its next
# scheduled run picks up the new binary, so no restart here.
sudo systemctl restart seo-insight-web
sudo systemctl restart seo-insight-analytics

echo "✓ Deploy done. Tail logs with:"
echo "    journalctl -u seo-insight-web -u seo-insight-analytics -u seo-insight-gsc-worker -f"

# Dernier message du script, donc le plus visible. Le code EST déployé (l'app
# tourne sur la nouvelle version) : un écart d'unités n'annule pas ce déploiement,
# il signale que la planification ou la configuration des services est en retard
# sur le dépôt. D'où un avertissement et non un échec.
if [ ${#SYSTEMD_DRIFT[@]} -gt 0 ]; then
	echo
	echo "⚠ Unités systemd en retard sur le dépôt :"
	printf '    · %s\n' "${SYSTEMD_DRIFT[@]}"
	echo
	echo "  Le code est déployé, mais ces unités ne le sont pas. Pour les installer"
	echo "  (opération root explicite — voir l'en-tête du script) :"
	echo "      sudo $(pwd)/deploy/sync-systemd.sh"
	echo
	echo "  ⚠ Cela peut ACTIVER la sync Search Console, qui n'a jamais tourné en"
	echo "    prod : son minuteur est en OnBootSec=10min, donc sur une machine"
	echo "    allumée depuis longtemps l'échéance est déjà dépassée et le premier"
	echo "    run part dans la foulée. L'app web doit être debout — elle l'est,"
	echo "    elle vient d'être redémarrée ci-dessus."
fi
