#!/bin/bash
# HTTP-01 + 自动改 Nginx（支持宝塔/aaPanel路径）
set -euo pipefail

GREEN='\033[0;32m'; YELLOW='\033[1;33m'; RED='\033[0;31m'; NC='\033[0m'
CERTBOT_EMAIL="dwawad@gmail.com"
LOCK_FILE="/var/lock/certbot_script.lock"

# ===== 最终状态（默认失败，后续按结果覆盖） =====
FINAL_STATUS="失败"

[ -f "$LOCK_FILE" ] && { echo -e "${RED}错误: 另一个实例正在运行${NC}"; echo -e "\n$DOMAIN $FINAL_STATUS"; exit 1; }
trap 'rm -f "$LOCK_FILE"' EXIT
touch "$LOCK_FILE"

if [ $# -lt 1 ]; then
  echo -e "${RED}错误: 请提供域名${NC}"
  echo "用法: $0 <域名[,更多域名]> [--test] [--no-redirect]"
  echo -e "\n$DOMAIN $FINAL_STATUS"
  exit 1
fi

DOMAINS_RAW="$1"
TEST_MODE=false
ENABLE_REDIRECT=true
[[ "${2:-}" == "--test" || "${3:-}" == "--test" ]] && TEST_MODE=true
[[ "${2:-}" == "--no-redirect" || "${3:-}" == "--no-redirect" ]] && ENABLE_REDIRECT=false

[ "$(id -u)" != "0" ] && { echo -e "${RED}错误: 必须以 root 运行${NC}"; echo -e "\n$DOMAIN $FINAL_STATUS"; exit 1; }

command -v certbot >/dev/null 2>&1 || { echo -e "${RED}错误: 未安装 certbot${NC}"; echo -e "\n$DOMAIN $FINAL_STATUS"; exit 1; }
certbot plugins 2>/dev/null | grep -q nginx || { echo -e "${RED}错误: 未安装 certbot-nginx 插件${NC}"; echo -e "\n$DOMAIN $FINAL_STATUS"; exit 1; }
echo -e "${GREEN}certbot 与 nginx 插件已就绪${NC}"

# --- 探测 nginx 配置与二进制（优先宝塔路径） ---
NGX_CONF_CAND=(
  "/www/server/nginx/conf/nginx.conf"
  "/etc/nginx/nginx.conf"
  "/usr/local/nginx/conf/nginx.conf"
)
NGINX_MAIN_CONF=""
for f in "${NGX_CONF_CAND[@]}"; do [ -f "$f" ] && { NGINX_MAIN_CONF="$f"; break; }; done
if [ -z "$NGINX_MAIN_CONF" ]; then
  echo -e "${RED}错误: 未找到 nginx 主配置文件${NC}"
  echo -e "\n$DOMAIN $FINAL_STATUS"
  exit 1
fi

NGX_ROOT="$(dirname "$NGINX_MAIN_CONF")"
if [ -x "/www/server/nginx/sbin/nginx" ]; then
  NGX_CTL="/www/server/nginx/sbin/nginx"
else
  NGX_CTL="$(command -v nginx || true)"
fi
if [ -z "${NGX_CTL:-}" ]; then
  echo -e "${RED}错误: 未找到 nginx 可执行文件${NC}"
  echo -e "\n$DOMAIN $FINAL_STATUS"
  exit 1
fi

cp -a "$NGINX_MAIN_CONF" "${NGINX_MAIN_CONF}.bak.$(date +%s)"
echo -e "${GREEN}备份 nginx 主配置: ${NGINX_MAIN_CONF}.bak.*${NC}"

echo -e "${YELLOW}提示: 确保 80 端口对外可达；如使用 Cloudflare，申请时不要强制跳转到 HTTPS。${NC}"
if command -v firewall-cmd >/dev/null 2>&1; then
  firewall-cmd --add-service=http --permanent >/dev/null 2>&1 || true
  firewall-cmd --add-service=https --permanent >/dev/null 2>&1 || true
  firewall-cmd --reload >/dev/null 2>&1 || true
fi

IFS=',' read -r -a DOMAINS_ARR <<< "$DOMAINS_RAW"
DOMAIN_ARGS=(); for d in "${DOMAINS_ARR[@]}"; do d=$(echo "$d" | xargs); [ -n "$d" ] && DOMAIN_ARGS+=( -d "$d" ); done
if [ ${#DOMAIN_ARGS[@]} -eq 0 ]; then
  echo -e "${RED}错误: 域名参数为空${NC}"
  echo -e "\n$DOMAIN $FINAL_STATUS"
  exit 1
fi

# 为了和你原打印保持一致，这里取第一个域名作为 $DOMAIN
DOMAIN="$(echo "${DOMAINS_ARR[0]}" | xargs)"

echo -e "${YELLOW}开始为域名申请（HTTP-01）并自动配置 Nginx...${NC}"

BASE_ARGS=( --nginx "${DOMAIN_ARGS[@]}" --email "$CERTBOT_EMAIL" --agree-tos --non-interactive )
BASE_ARGS+=( --nginx-server-root "$NGX_ROOT" --nginx-ctl "$NGX_CTL" )
$TEST_MODE && BASE_ARGS+=( --test-cert )
$ENABLE_REDIRECT && BASE_ARGS+=( --redirect ) || BASE_ARGS+=( --no-redirect )
BASE_ARGS+=( --preferred-challenges http )

set +e
certbot "${BASE_ARGS[@]}"
CB_STATUS=$?
set -e

if [ $CB_STATUS -ne 0 ]; then
  echo -e "${RED}证书申请/安装失败，尝试回滚 Nginx 备份${NC}"
  cp -a "${NGINX_MAIN_CONF}.bak."* "$NGINX_MAIN_CONF" 2>/dev/null || true
  "$NGX_CTL" -t && "$NGX_CTL" -s reload || true
  FINAL_STATUS="失败"
  echo -e "${RED}失败代码: $CB_STATUS${NC}"
  echo -e "${YELLOW}常见原因：\n- Cloudflare 边缘“始终使用 HTTPS”未关闭\n- 80 端口未通或被拦\n- Nginx 配置冲突/语法错误${NC}"
  echo -e "\n$DOMAIN $FINAL_STATUS"
  exit $CB_STATUS
fi

# 验证并重载（优先使用 nginx -s reload）
"$NGX_CTL" -t
if ! "$NGX_CTL" -s reload 2>/dev/null; then
  systemctl reload nginx 2>/dev/null || systemctl restart nginx 2>/dev/null || true
fi
echo -e "${GREEN}Nginx 已重载${NC}"

# 成功后的状态
if $TEST_MODE; then
  FINAL_STATUS="测试模式: 成功"
else
  FINAL_STATUS="成功"
fi

echo -e "${YELLOW}检查/启用自动续期...${NC}"
if systemctl list-unit-files | grep -q '^certbot\.timer'; then
  systemctl enable --now certbot.timer
  systemctl status certbot.timer
elif systemctl list-unit-files | grep -q '^certbot-renew\.timer'; then
  systemctl enable --now certbot-renew.timer
  systemctl status certbot-renew.timer
elif systemctl list-units | grep -q 'snap\.certbot\.renew\.service'; then
  systemctl enable --now snap.certbot.renew.service
  systemctl status snap.certbot.renew.service
else
  echo -e "${YELLOW}未发现 systemd timer，可能走 cron 续期（不影响使用）。${NC}"
fi

# ===== 和你原脚本一致的最终输出（用于判定） =====
echo -e "\n$DOMAIN $FINAL_STATUS"
