#!/usr/bin/env bash
# Deploys one commit to staging.passlabb.com (cPanel "Setup Node.js App", Passenger).
# Run by GitHub Actions after every push to the "staging" branch: the workflow uploads app.tgz (the app folder of
# that commit) and this script to ~/passlabb-staging-incoming/, then runs:  bash deploy-staging.sh <commit>
# The server keeps its own .env (staging database, STAGING=1, STAGING_PASSWORD) and uploads; they are never replaced.
set -euo pipefail
SHA="${1:?commit}"
APP="$HOME/passlabb-staging/app"            # cPanel Node.js app "Application root": passlabb-staging/app
IN="$HOME/passlabb-staging-incoming"
TMP="$IN/release-$SHA"

echo "== Staging deploy of $SHA"
[ -f "$APP/.env" ] || { echo "Missing $APP/.env: create it first (see deploy/STAGING.md)."; exit 1; }
grep -q '^STAGING=1' "$APP/.env" || { echo "$APP/.env must contain STAGING=1: refusing to deploy, this may not be the staging app."; exit 1; }

rm -rf "$TMP"; mkdir -p "$TMP"
tar -xzf "$IN/app.tgz" -C "$TMP"
# copy the new code over the app folder; keep the server's .env, uploads, installed modules and Passenger files
rsync -a --delete --exclude ".env" --exclude "uploads/" --exclude "node_modules" --exclude "tmp/" --exclude ".htaccess" "$TMP/app/" "$APP/"
rm -rf "$TMP"

# the Node version chosen in cPanel for this app
ACT="$(ls -d "$HOME"/nodevenv/passlabb-staging/app/*/bin/activate 2>/dev/null | sort -V | tail -1 || true)"
if [ -n "$ACT" ]; then
  # shellcheck disable=SC1090
  source "$ACT"
fi
cd "$APP"
echo "== Node $(node -v)"
npm install --omit=dev --no-audit --no-fund
npm run migrate
node scripts/import-site.mjs --update-code
mkdir -p tmp && touch tmp/restart.txt
echo "== Staging updated to $SHA"
