#!/usr/bin/env bash
# Deploys the latest code on the VPS. Run as the passlabb user:
#   bash /srv/passlabb/deploy/scripts/deploy.sh [--first-run]
set -euo pipefail
APP_DIR=/srv/passlabb
cd "$APP_DIR"

echo "==> Pull"
git fetch --quiet origin
git reset --hard origin/main

cd app
echo "==> Dependencies (optional pg driver; the app also runs without it)"
npm install --omit=dev --no-audit --no-fund || echo "   npm install failed: using the built-in PostgreSQL client"

echo "==> Database migrations"
npm run --silent migrate

if [ "${1:-}" = "--first-run" ]; then
  echo "==> Importing the catalogue (experiences, cities, routes, blog)"
  node scripts/import-catalogue.mjs
fi

echo "==> Passlabb site (new code; the settings published from the Ops Hub and all data are kept)"
node scripts/import-site.mjs --update-code

echo "==> Restart"
sudo systemctl enable --now passlabb-app.service passlabb-emails.timer passlabb-prices.timer passlabb-fx.timer passlabb-cleanup.timer passlabb-backup.timer 2>/dev/null || true
sudo systemctl restart passlabb-app.service
sleep 2
curl -fsS http://127.0.0.1:3000/healthz && echo "  app healthy"
