#!/usr/bin/env bash
# nginx-test.sh — CI 环境下校验 nginx 配置，用自签桩证书代替真实 Let's Encrypt 证书。
# 依赖: docker、openssl
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
CERT_DIR="$(mktemp -d)"

cleanup() {
  rm -rf "$CERT_DIR"
}
trap cleanup EXIT INT TERM

echo "→ 生成自签桩证书 ..."

# 三个需要证书的域名
for domain in vpn.51yanmei.com blog.51yanmei.com jiu.51yanmei.com; do
  mkdir -p "${CERT_DIR}/live/${domain}"
  openssl req -x509 -nodes -newkey ec -pkeyopt ec_paramgen_curve:P-256 -days 1 \
    -keyout "${CERT_DIR}/live/${domain}/privkey.pem" \
    -out    "${CERT_DIR}/live/${domain}/fullchain.pem" \
    -subj   "/CN=${domain}" 2>/dev/null
done

# options-ssl-nginx.conf 桩（nginx -t 仅检查文件可读，不校验内容）
printf '# stub\n' > "${CERT_DIR}/options-ssl-nginx.conf"

# ssl-dhparams.pem 桩（生成 512-bit DH，足够 nginx 解析，CI 不要求安全强度）
openssl dhparam -out "${CERT_DIR}/ssl-dhparams.pem" 512 2>/dev/null

# 桩目录（nginx alias/root 在 -t 时不校验是否存在，但 volume 挂载需目录存在）
mkdir -p "${CERT_DIR}/jiu/images" "${CERT_DIR}/jiu/web" "${CERT_DIR}/jiu/marketing"
mkdir -p "${CERT_DIR}/www-pay"

echo "→ 运行 nginx -t ..."

docker run --rm \
  -v "${REPO_ROOT}/deploy/edge/nginx.conf:/etc/nginx/nginx.conf:ro" \
  -v "${REPO_ROOT}/deploy/edge/stream.conf:/etc/nginx/stream.conf:ro" \
  -v "${REPO_ROOT}/deploy/edge/conf.d:/etc/nginx/conf.d:ro" \
  -v "${CERT_DIR}:/etc/letsencrypt:ro" \
  -v "${CERT_DIR}/jiu:/opt/jiu:ro" \
  -v "${CERT_DIR}/www-pay:/var/www/pay:ro" \
  nginx:1.27-alpine nginx -t

echo "✅ nginx 配置校验通过。"
