#!/usr/bin/env bash
# deploy.sh —— 幂等部署(免 root)。CI 与手动均可。
#   - 总是确保 singbox(Hy2)在跑;
#   - edge:若宿主 nginx 仍在(未切换)则只校验配置、不启动(避免抢 80/443);
#           宿主 nginx 已停(已切换)则正常拉起。
# 首次 nginx 切换由 cutover.sh(需 root 一次)完成。
set -euo pipefail
cd "$(dirname "$0")/.."   # -> deploy/

EDGE_IMAGE="nginx:1.27-alpine"

echo "==> [1/4] 生成/复用密钥与证书"
./scripts/gen-secrets.sh

echo "==> [2/4] 渲染配置"
# shellcheck disable=SC1091
source ./secrets/pangolin.env
sed "s|__HY2_PASSWORD__|${HY2_PASSWORD}|g" ./singbox/config.tmpl.json > ./singbox/config.json

echo "==> [3/4] 拉起 singbox(Hy2)"
docker-compose -p pangolin up -d singbox
docker-compose -p pangolin ps singbox

echo "==> [4/4] edge(分发层)"
edge_validate() {
  docker run --rm \
    -v "$PWD/edge/nginx.conf:/etc/nginx/nginx.conf:ro" \
    -v "$PWD/edge/stream.conf:/etc/nginx/stream.conf:ro" \
    -v "$PWD/edge/conf.d:/etc/nginx/conf.d:ro" \
    -v /etc/letsencrypt:/etc/letsencrypt:ro \
    -v /opt/jiu:/opt/jiu:ro \
    -v /var/www/pay:/var/www/pay:ro \
    "$EDGE_IMAGE" nginx -t
}
if systemctl is-active --quiet nginx 2>/dev/null; then
  echo "    宿主 nginx 仍在运行 → 仅校验 edge 配置,不启动(切换请跑 cutover.sh)"
  edge_validate && echo "    edge 配置校验通过 ✅"
else
  echo "    宿主 nginx 未运行 → 构建并拉起 edge"
  edge_validate
  docker build -t pangolin-edge:local ./edge
  docker-compose -p pangolin up -d edge
  docker-compose -p pangolin ps edge
fi

./scripts/print-clients.sh
echo "==> 完成 ✅"
