#!/usr/bin/env bash
# g2.tkmind.cn：Let's Encrypt + 阿里云 DNS-01，供 Caddy :8444 使用
#
# 前置（阿里云控制台）：
#   1. 云解析 DNS 添加域名 tkmind.cn，NS 改到阿里云（见脚本末尾说明）
#   2. 添加 A 记录：g2 -> 58.38.22.103
#   3. RAM 创建 AccessKey，权限 AliyunDNSFullAccess
#   4. cp scripts/g2-aliyun-cert.env.example scripts/g2-aliyun-cert.env 并填入密钥
#
# 用法：
#   ./scripts/install-g2-aliyun-cert.sh
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
ENV_FILE="${ROOT}/scripts/g2-aliyun-cert.env"
CADDYFILE="${ROOT}/scripts/g2-lb.Caddyfile"
CADDY="/opt/homebrew/bin/caddy"
ACME="${HOME}/.acme.sh/acme.sh"
CERT_DIR="${HOME}/Downloads/g2.tkmind.cn-certs"
DOMAIN="${G2_DOMAIN:-g2.tkmind.cn}"
GUI="gui/$(id -u)"

die() { echo "错误: $*" >&2; exit 1; }

[[ -f "$ENV_FILE" ]] || die "请先创建 ${ENV_FILE}（参考 g2-aliyun-cert.env.example）"
# shellcheck disable=SC1090
source "$ENV_FILE"
[[ -n "${Ali_Key:-}" && "${Ali_Key}" != YOUR_* ]] || die "请在 ${ENV_FILE} 填入 Ali_Key"
[[ -n "${Ali_Secret:-}" && "${Ali_Secret}" != YOUR_* ]] || die "请在 ${ENV_FILE} 填入 Ali_Secret"
DOMAIN="${G2_DOMAIN:-g2.tkmind.cn}"

[[ -x "$ACME" ]] || die "未找到 acme.sh，请先安装: curl https://get.acme.sh | sh"

export Ali_Key Ali_Secret

echo "==> 签发证书（DNS-01 / 阿里云）: ${DOMAIN}"
"$ACME" --set-default-ca --server letsencrypt
"$ACME" --issue --dns dns_ali -d "$DOMAIN" --keylength ec-256

CERT_HOME="${HOME}/.acme.sh/${DOMAIN}_ecc"
[[ -d "${HOME}/.acme.sh/${DOMAIN}_ecc" ]] && CERT_HOME="${HOME}/.acme.sh/${DOMAIN}_ecc"
[[ -d "${HOME}/.acme.sh/${DOMAIN}" ]] && CERT_HOME="${HOME}/.acme.sh/${DOMAIN}"
[[ -f "${CERT_HOME}/fullchain.cer" ]] || die "证书签发失败，请检查阿里云 DNS 权限与域名是否在云解析"

echo "==> 配置 Caddy 使用证书"
cp "$CADDYFILE" "${CADDYFILE}.bak-$(date +%Y%m%d-%H%M%S)"

python3 <<PY
from pathlib import Path
path = Path("${CADDYFILE}")
text = path.read_text()
cert = "${CERT_HOME}/fullchain.cer"
key = "${CERT_HOME}/${DOMAIN}.key"
block = f'''# g2.tkmind.cn：公网入口转发到 Studio 本机 H5 (:8081)
{DOMAIN} {{
\ttls {cert} {key}

\treverse_proxy 127.0.0.1:8081 {{'''
import re
text = re.sub(
    r'# g2\.tkmind\.cn：.*?\n' + re.escape("${DOMAIN}") + r' \{.*?\n\treverse_proxy 127\.0\.0\.1:8081 \{',
    block,
    text,
    count=1,
    flags=re.DOTALL,
)
path.write_text(text)
PY

"$CADDY" validate --config "$CADDYFILE"

echo "==> 安装续期后自动 reload Caddy"
RELOAD="launchctl kickstart -k ${GUI}/cn.tkmind.g2-lb"
"$ACME" --install-cert -d "$DOMAIN" \
  --reloadcmd "$RELOAD"

launchctl kickstart -k "${GUI}/cn.tkmind.g2-lb" 2>/dev/null || true
sleep 2

mkdir -p "$CERT_DIR"
cp "${CERT_HOME}/fullchain.cer" "${CERT_DIR}/fullchain.pem"
cp "${CERT_HOME}/${DOMAIN}.key" "${CERT_DIR}/${DOMAIN}.key"
cp "${CERT_HOME}/fullchain.cer" "${CERT_DIR}/g2.tkmind.cn.crt"
openssl x509 -in "${CERT_DIR}/fullchain.pem" -noout -subject -issuer -dates

echo ""
echo "==> 完成"
echo "    证书: ${CERT_HOME}/"
echo "    导出: ${CERT_DIR}/"
echo "    验证: curl -s https://${DOMAIN}/api/status"
echo ""
echo "==> 阿里云 DNS 迁移检查清单"
echo "    1. 云解析 DNS 已添加 tkmind.cn"
echo "    2. 域名注册商 NS 已改为阿里云（例如 vip1.alidns.com / vip2.alidns.com）"
echo "    3. A 记录 g2 -> ${G2_PUBLIC_IP:-58.38.22.103}"
echo "    4. 删除 Cloudflare 上 g2 的 CNAME/代理记录，避免冲突"
echo "    5. dig @223.5.5.5 +short ${DOMAIN} A  应返回 ${G2_PUBLIC_IP:-58.38.22.103}"
