#!/usr/bin/env bash
# Update the running server to a new version. Called by the GitHub deploy
# workflow over SSH, or run by hand after `git pull`.
#
#   bash scripts/deploy.sh            # build locally from this checkout
#   API_IMAGE=... WEB_IMAGE=... bash scripts/deploy.sh   # use prebuilt images (CI)
set -euo pipefail
cd "$(dirname "$0")/.."

echo ">> Backup before deploy"
bash scripts/backup.sh || { echo "backup failed: aborting deploy"; exit 1; }

if [ -n "${API_IMAGE:-}" ]; then
  echo ">> Pulling $API_IMAGE and $WEB_IMAGE"
  export API_IMAGE WEB_IMAGE
  docker compose pull api worker web migrate
else
  echo ">> Building"
  docker compose build
fi

echo ">> Migrations (forward-compatible: old code must keep working during this step)"
docker compose --profile tools run --rm migrate

echo ">> Restarting services"
docker compose up -d --remove-orphans

echo ">> Waiting for health"
for i in $(seq 1 30); do
  if docker compose exec -T api node -e "fetch('http://localhost:4000/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"; then
    echo "healthy"; docker image prune -f >/dev/null; exit 0
  fi
  sleep 2
done
echo "API did not become healthy. Check: docker compose logs api --tail 100"
exit 1
