#!/usr/bin/env bash
# Run ON production server — 自动识别 Docker / Supervisor
#
# Usage (on server):
#   cd /opt/nexus && sudo bash deploy/deploy-on-server.sh
#   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    — Supervisor 模式跳过热更新前端 tar
#   NEXUS_DEPLOY_PATH  — 覆盖自动检测路径

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=./detect_deploy_runtime.sh
source "${SCRIPT_DIR}/detect_deploy_runtime.sh"

DEPLOY_PATH="$(resolve_nexus_root "${NEXUS_DEPLOY_PATH:-}" 2>/dev/null || true)"
if [[ -z "$DEPLOY_PATH" ]]; then
  echo "ERROR: cannot resolve Nexus root" >&2
  exit 1
fi
cd "${DEPLOY_PATH}"

RUNTIME="$(detect_nexus_runtime "$DEPLOY_PATH")"
PORT="$(nexus_publish_port_for "$DEPLOY_PATH")"

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

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

if [[ "$RUNTIME" == "docker" ]]; then
  echo "▶ Docker upgrade (pull + rebuild)..."
  exec env NEXUS_ROOT="$DEPLOY_PATH" bash "$DEPLOY_PATH/deploy/nexus-1panel.sh" upgrade
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:${PORT}/health" || true)
SPA=$(curl -s -o /dev/null -w '%{http_code}' "http://127.0.0.1:${PORT}/app/" || echo "000")
echo "  /health → ${HEALTH}"
echo "  /app/   → ${SPA}"

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