#!/usr/bin/env bash
# Run ON production server (宝塔终端 / ssh root@47.254.123.106)
# Pulls latest main from Gitea and restarts Nexus. Frontend tar must be uploaded separately
# if you did not build on this machine.
#
# Usage (on server):
#   cd /www/wwwroot/api.synaglobal.vip
#   bash deploy/deploy-on-server.sh
#
# Optional env:
#   NEXUS_GITEA_TOKEN  — if git pull needs auth
#   SKIP_FRONTEND=1    — backend only

set -euo pipefail

DEPLOY_PATH="${NEXUS_DEPLOY_PATH:-/www/wwwroot/api.synaglobal.vip}"
cd "${DEPLOY_PATH}"

echo "═══ Nexus server-side deploy ═══"
echo "Path: ${DEPLOY_PATH}"

if [ -n "${NEXUS_GITEA_TOKEN:-}" ]; then
  git remote set-url origin "http://admin:${NEXUS_GITEA_TOKEN}@66.154.115.8:3000/admin/Nexus.git"
fi

echo "▶ git fetch + reset --hard origin/main..."
git fetch --all
git reset --hard origin/main
echo "  HEAD: $(git log -1 --oneline)"

echo "▶ supervisorctl restart nexus..."
supervisorctl restart nexus

if [ -f /tmp/nexus-frontend.tar.gz ] && [ "${SKIP_FRONTEND:-0}" != "1" ]; then
  echo "▶ extract /tmp/nexus-frontend.tar.gz..."
  tar xzf /tmp/nexus-frontend.tar.gz -C web/app
  rm -f /tmp/nexus-frontend.tar.gz
  if [ -f deploy/prune_frontend_assets.py ]; then
    python3 deploy/prune_frontend_assets.py --dry-run
    python3 deploy/prune_frontend_assets.py
  fi
  supervisorctl restart nexus
fi

sleep 3
HEALTH=$(curl -s http://127.0.0.1:8600/health || true)
SPA=$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8600/app/ || echo "000")
echo "  /health → ${HEALTH}"
echo "  /app/   → ${SPA}"

if [ "${HEALTH}" = "ok" ] && [ "${SPA}" = "200" ]; then
  echo "✓ Server deploy OK"
else
  echo "✗ Verify failed — check: supervisorctl status nexus" >&2
  exit 1
fi
