#!/usr/bin/env bash
# 為 00002359.tech 加上 443 監聽 + Let's Encrypt 憑證（寫入面板原本的 site vhost，令 extension deny 規則同時生效）
set -euo pipefail

CONF=/www/server/panel/vhost/nginx/00002359.tech.conf
LIVE=/etc/letsencrypt/live/00002359.tech
BAK="/root/fse_vhost_$(date +%Y%m%d_%H%M%S).conf.bak"

cp -a "$CONF" "$BAK"
echo "BACKUP=$BAK"

python3 - "$CONF" "$LIVE" <<'PY'
import sys, re
conf, live = sys.argv[1], sys.argv[2]
s = open(conf, encoding='utf-8').read()

if 'ssl_certificate' in s:
    print('SSL_ALREADY_IN_CONF'); sys.exit(0)

# 443 監聽（保留 80 俾 ACME 同 CF Flexible 後備）
s = s.replace('    listen 80;\n', '    listen 80;\n    listen 443 ssl;\n', 1)

block = (
    "    ssl_certificate %s/fullchain.pem;\n"
    "    ssl_certificate_key %s/privkey.pem;\n"
    "    ssl_protocols TLSv1.2 TLSv1.3;\n"
    "    ssl_ciphers HIGH:!aNULL:!MD5;\n"
    "    ssl_prefer_server_ciphers on;\n"
    "    ssl_session_cache shared:SSL:10m;\n"
    "    ssl_session_timeout 10m;\n" % (live, live)
)

m = re.search(r'([ \t]*#SSL-START[^\n]*\n)', s)
if m:
    s = s[:m.end()] + block + s[m.end():]
else:
    i = s.index('    server_name')
    s = s[:i] + block + s[i:]
    print('FALLBACK_INSERT_AFTER_SERVER_NAME')

open(conf, 'w', encoding='utf-8').write(s)
print('CONF_PATCHED')
PY

nginx -t 2>&1 | tail -3
/etc/init.d/nginx reload >/dev/null 2>&1 || nginx -s reload
sleep 1
echo '--- listeners ---'
ss -lntp | grep -E ':(80|443)\s' | awk '{print $1, $4, $6}' | head -4
echo '--- direct 443 ---'
curl -s -o /dev/null -w "root code=%{http_code}\n" --resolve 00002359.tech:443:127.0.0.1 --max-time 20 https://00002359.tech/
curl -s -o /dev/null -w "login code=%{http_code} size=%{size_download}\n" --resolve 00002359.tech:443:127.0.0.1 --max-time 20 https://00002359.tech/login.php
echo '--- deny still active on 443 ---'
for p in /api/worker_list.php /views/workers.php /lib/db.php /uploads/ ; do
  printf "%s -> %s\n" "$p" "$(curl -s -o /dev/null -w '%{http_code}' --resolve 00002359.tech:443:127.0.0.1 --max-time 15 https://00002359.tech$p)"
done
echo '--- cert expiry ---'
openssl x509 -enddate -noout -in "$LIVE/cert.pem"
