#!/usr/bin/env bash
#
# Server-side deploy for the Bifrost portal. Run ON THE VPS, as the `bifrost`
# service user, from inside the checkout (/opt/bifrost-portal).
#
#   cd /opt/bifrost-portal && ./scripts/deploy.sh
#
# Pulls latest, installs deps (rebuilding the native better-sqlite3 for this
# box's arch), builds, migrates, and restarts the service. Idempotent and
# safe to re-run. Does NOT touch the database file or uploads — those live in
# /var/lib/bifrost-portal and persist across deploys.

set -euo pipefail

APP_DIR="${APP_DIR:-/opt/bifrost-portal}"
SERVICE="${SERVICE:-bifrost-portal}"
BRANCH="${BRANCH:-master}"
ENV_FILE="${ENV_FILE:-/opt/bifrost-portal/.env}"

cd "$APP_DIR"

echo "==> Loading $ENV_FILE for migrate (BIFROST_DB_PATH)"
set -a; # shellcheck disable=SC1090
source "$ENV_FILE"; set +a

echo "==> Fetching origin/$BRANCH"
git fetch --prune origin
git checkout "$BRANCH"
git reset --hard "origin/$BRANCH"

echo "==> Installing dependencies (frozen lockfile)"
# pnpm rebuilds better-sqlite3 for this machine's arch via onlyBuiltDependencies.
pnpm install --frozen-lockfile

echo "==> Building"
pnpm build

echo "==> Applying database migrations -> $BIFROST_DB_PATH"
node scripts/migrate.js

echo "==> Restarting $SERVICE"
# Non-interactive: if fenja has the NOPASSWD rule for this unit it restarts
# silently; otherwise we don't hang on a password prompt — we tell the
# operator to restart as a sudo user.
if sudo -n systemctl restart "$SERVICE" 2>/dev/null; then
  echo "    restarted"
else
  echo "    !! could not restart without a password."
  echo "    Run as a sudo user:  sudo systemctl restart $SERVICE"
  echo "    (or grant fenja the NOPASSWD rule — see DEPLOY.md §6)"
  exit 1
fi

echo "==> Waiting for health"
sleep 2
# status is read-only — no sudo needed
systemctl --no-pager --lines=0 status "$SERVICE" || true

echo "==> Deploy complete: $(git rev-parse --short HEAD)"
