#!/usr/bin/env bash
# 修復 188 registry.wooo.work HTTP-01 renewal route 並強制更新憑證。
# 用法：在 188 主機以 root 執行：
#   sudo bash /tmp/fix-188-registry-certbot-renewal.sh

set -euo pipefail

CONF_AVAILABLE="/etc/nginx/sites-available/internal-tools-https.conf"
CONF_ENABLED="/etc/nginx/sites-enabled/internal-tools-https.conf"
WEBROOT="/var/www/certbot"
DOMAIN="registry.wooo.work"
STAMP="$(date +%Y%m%d%H%M%S)"

if [ "$(id -u)" -ne 0 ]; then
  echo "ERROR: 請在 188 主機用 root/sudo 執行。" >&2
  exit 1
fi

if [ ! -f "$CONF_AVAILABLE" ]; then
  echo "ERROR: 找不到 $CONF_AVAILABLE" >&2
  exit 1
fi

cp "$CONF_AVAILABLE" "${CONF_AVAILABLE}.bak-${STAMP}-registry-http01"
mkdir -p "${WEBROOT}/.well-known/acme-challenge"
chmod 0755 "$WEBROOT" "${WEBROOT}/.well-known" "${WEBROOT}/.well-known/acme-challenge"

if ! grep -q "AWOOOI internal-tools HTTP-01 managed block" "$CONF_AVAILABLE"; then
  tmp="$(mktemp)"
  cat >"$tmp" <<'EOF'
# AWOOOI internal-tools HTTP-01 managed block
server {
    listen 80;
    server_name
        gitea.wooo.work
        sentry.wooo.work
        langfuse.wooo.work
        harbor.wooo.work
        registry.wooo.work
        stock.wooo.work;

    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        return 301 https://$host$request_uri;
    }
}

EOF
  cat "$CONF_AVAILABLE" >>"$tmp"
  install -o root -g root -m 0644 "$tmp" "$CONF_AVAILABLE"
  rm -f "$tmp"
fi

ln -sfn "$CONF_AVAILABLE" "$CONF_ENABLED"
nginx -t
systemctl reload nginx

probe="awoooi-certbot-${STAMP}"
printf '%s\n' "$probe" >"${WEBROOT}/.well-known/acme-challenge/${probe}"
trap 'rm -f "${WEBROOT}/.well-known/acme-challenge/${probe}"' EXIT

body="$(curl -fsS --max-time 10 "http://${DOMAIN}/.well-known/acme-challenge/${probe}")"
if [ "$body" != "$probe" ]; then
  echo "ERROR: HTTP-01 webroot probe failed for ${DOMAIN}" >&2
  exit 1
fi

if [ -x /snap/bin/certbot ]; then
  CERTBOT=/snap/bin/certbot
else
  CERTBOT=/usr/bin/certbot
fi

"$CERTBOT" renew --cert-name "$DOMAIN" --force-renewal --deploy-hook "systemctl reload nginx"
systemctl reload nginx
systemctl reset-failed certbot.service snap.certbot.renew.service 2>/dev/null || true

echo | openssl s_client -servername "$DOMAIN" -connect "${DOMAIN}:443" 2>/dev/null \
  | openssl x509 -noout -subject -issuer -dates

echo "REGISTRY_CERTBOT_RENEWAL_OK"
