#!/usr/bin/env bash
# 在 105 服务器上为 w.tkmind.cn 签发 Let's Encrypt 并 reload nginx
set -euo pipefail

DOMAIN=w.tkmind.cn
WEBROOT=/root/wordloop/frontend/dist
EMAIL="${CERTBOT_EMAIL:-admin@tkmind.cn}"

# 先确保 80 可访问（用于 ACME）
cp /root/wordloop/deploy/wordloop-locations.inc /etc/nginx/conf.d/wordloop-locations.inc
cp /root/wordloop/deploy/nginx-production.conf /etc/nginx/conf.d/wordloop.conf
# 若尚无证书，临时注释 443 块会导致语法错误 — 仅用 certbot 独立签发的 80 配置
if [ ! -f "/etc/letsencrypt/live/${DOMAIN}/fullchain.pem" ]; then
  cat > /etc/nginx/conf.d/wordloop.conf <<'NGINX80'
server {
    listen 80;
    server_name w.tkmind.cn;
    root /root/wordloop/frontend/dist;
    location /.well-known/acme-challenge/ { root /root/wordloop/frontend/dist; }
    location / { try_files $uri $uri/ /index.html; }
}
NGINX80
  nginx -t && systemctl reload nginx
  certbot certonly --webroot -w "$WEBROOT" -d "$DOMAIN" \
    --non-interactive --agree-tos -m "$EMAIL" \
    --preferred-challenges http
fi

cp /root/wordloop/deploy/wordloop-locations.inc /etc/nginx/conf.d/wordloop-locations.inc
cp /root/wordloop/deploy/nginx-production.conf /etc/nginx/conf.d/wordloop.conf
nginx -t
systemctl reload nginx
echo "SSL ready for https://${DOMAIN}/"
