#!/usr/bin/env bash
# rollback.sh —— 一键回滚:停 pangolin-edge 容器,恢复宿主 nginx(需 root)。
#   sudo bash /home/ec2-user/pangolin/scripts/rollback.sh
# 适用:切换失败、或切换后发现问题,要回到"宿主 nginx 接管 443/80"的原状态。
# 注:singbox(Hy2/UDP443)与宿主 nginx 不冲突,默认保留运行;如需一并停,见文档。
set -euo pipefail

if [[ "$(id -u)" -ne 0 ]]; then
  echo "请以 root 运行:sudo bash $0" >&2
  exit 1
fi

echo "==> [1/3] 停 edge 容器(释放 80/443)"
# 必须先停容器,否则宿主 nginx 会因端口占用起不来
docker-compose -p pangolin stop edge 2>/dev/null || docker stop pangolin-edge 2>/dev/null || true

echo "==> [2/3] 恢复宿主 nginx"
systemctl enable nginx >/dev/null 2>&1 || true
systemctl start nginx
systemctl is-active --quiet nginx && echo "    宿主 nginx 已启动" || { echo "    !! 启动失败,见文档排查"; exit 1; }

echo "==> [3/3] 健康检查"
sleep 1
fail=0
echo | timeout 10 openssl s_client -connect 127.0.0.1:443 -servername www.cloudflare.com >/dev/null 2>&1 \
  && echo "    [REALITY] 443 握手 OK" || { echo "    [REALITY] 握手失败"; fail=1; }
for d in blog jiu vpn; do
  code="$(curl -ks -o /dev/null -w '%{http_code}' --resolve ${d}.51yanmei.com:443:127.0.0.1 https://${d}.51yanmei.com/ 2>/dev/null || echo 000)"
  echo "    [${d}] https -> ${code}"
  [[ "$code" =~ ^[2-4][0-9][0-9]$ ]] || fail=1
done

[[ "$fail" == "0" ]] && echo "==> 回滚完成 ✅ 已回到宿主 nginx" \
  || { echo "==> ⚠️ 已回到宿主 nginx 但检查未全过,见文档"; exit 1; }
