#!/bin/bash
# ═══════════════════════════════════════════════════════════════════
# tunnel-handler-th — sz 全面迁移批次脚本（特批通道一次执行，幂等可重跑）
# 用法: bash /var/www/dsh.456.xyz/sz-deploy-batch.sh
# 前置: 7 文件已 scp 至 /var/www/dsh.456.xyz/（frps frps.toml tunnel-log-shipper.py
#       install-log-shipper.sh deploy-sz.sh sz-deploy-batch.sh guiping_atsc_pubkey.txt）
# 内容: ① 搬运文件 ② 部署 frps(systemd) ③ 部署日志回传
#       ④ nginx vhost th.456.xyz(80 ACME → 443 autoindex) ⑤ certbot 签发
# 依赖: 阿里云安全组已放行 7000/7500/2233-2236（人类管理员控制台操作）
# ═══════════════════════════════════════════════════════════════════
set -uo pipefail

STAGE=/var/www/dsh.456.xyz
BASE=/var/www/th.456.xyz/tunnel-files
mkdir -p "$BASE" /opt/tunnel /var/www/certbot

echo "== [1/5] 搬运文件到文件中心 =="
for f in frps frps.toml tunnel-log-shipper.py install-log-shipper.sh deploy-sz.sh sz-deploy-batch.sh guiping_atsc_pubkey.txt; do
  if [ -f "$STAGE/$f" ]; then
    cp -f "$STAGE/$f" "$BASE/$f"
    echo "搬运 $f OK"
  else
    echo "⚠️ 缺 $f"
  fi
done

echo "== [2/5] 部署 frps =="
if [ -s "$BASE/frps" ] && [ -s "$BASE/frps.toml" ]; then
  cp -f "$BASE/frps" /opt/tunnel/frps
  cp -f "$BASE/frps.toml" /opt/tunnel/frps.toml
  chmod 755 /opt/tunnel/frps
  if [ ! -f /etc/systemd/system/frps.service ]; then
    cat > /etc/systemd/system/frps.service <<'SVC'
[Unit]
Description=frps - tunnel-handler-th hub (sz)
After=network.target

[Service]
Type=simple
ExecStart=/opt/tunnel/frps -c /opt/tunnel/frps.toml
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
SVC
    systemctl daemon-reload
    systemctl enable --now frps
    sleep 2
  else
    systemctl restart frps
  fi
  echo "frps: $(systemctl is-active frps)"
else
  echo "❌ frps 或 frps.toml 缺失，跳过"
fi

echo "== [3/5] 部署日志回传 =="
if [ -f "$BASE/tunnel-log-shipper.py" ]; then
  cp -f "$BASE/tunnel-log-shipper.py" /opt/tunnel/tunnel-log-shipper.py
  chmod 755 /opt/tunnel/tunnel-log-shipper.py
  if [ ! -f /etc/systemd/system/tunnel-log-shipper.service ]; then
    cat > /etc/systemd/system/tunnel-log-shipper.service <<'UNIT'
[Unit]
Description=Tunnel frps log shipper to atsc web
After=network-online.target

[Service]
ExecStart=/usr/bin/python3 /opt/tunnel/tunnel-log-shipper.py
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
UNIT
    systemctl daemon-reload
    systemctl enable tunnel-log-shipper >/dev/null 2>&1 || true
  fi
  systemctl restart tunnel-log-shipper
  echo "tunnel-log-shipper: $(systemctl is-active tunnel-log-shipper)"
else
  echo "❌ tunnel-log-shipper.py 缺失"
fi

echo "== [4/5] nginx vhost th.456.xyz（80 ACME 挑战）=="
cat > /etc/nginx/conf.d/th.456.xyz.conf <<'NGX'
server {
    listen 80;
    server_name th.456.xyz;

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

    location / {
        return 301 https://$host$request_uri;
    }
}
NGX
nginx -t && systemctl reload nginx && echo "nginx 80 OK"

echo "== [5/5] certbot 签发 + 443 vhost =="
if [ ! -d /etc/letsencrypt/live/th.456.xyz ]; then
  if command -v certbot >/dev/null 2>&1; then
    certbot certonly --webroot -w /var/www/certbot -d th.456.xyz \
      --non-interactive --agree-tos -m aysun@qq.com --keep-until-expiring \
      && echo "certbot 签发 OK" || echo "⚠️ certbot 签发失败"
  else
    echo "⚠️ certbot 未安装，跳过签发"
  fi
else
  echo "证书已存在，跳过签发"
fi
if [ -f /etc/letsencrypt/live/th.456.xyz/fullchain.pem ]; then
  cat > /etc/nginx/conf.d/th.456.xyz.conf <<'NGX'
server {
    listen 80;
    server_name th.456.xyz;

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

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

server {
    listen 443 ssl;
    http2 on;
    server_name th.456.xyz;

    ssl_certificate     /etc/letsencrypt/live/th.456.xyz/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/th.456.xyz/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_session_cache shared:THSSL:10m;

    root /var/www/th.456.xyz/tunnel-files;
    autoindex on;
    autoindex_exact_size off;
    autoindex_localtime on;

    location / {
        try_files $uri =404;
    }
}
NGX
  nginx -t && systemctl reload nginx && echo "nginx 443 OK"
else
  echo "⚠️ 证书未签发，443 vhost 未安装（后续手动补 certbot）"
fi

echo "== 汇总 =="
echo "frps: $(systemctl is-active frps 2>/dev/null || echo inactive)"
echo "shipper: $(systemctl is-active tunnel-log-shipper 2>/dev/null || echo inactive)"
echo "th.456.xyz: $(curl -s -o /dev/null -w '%{http_code}' --max-time 5 https://th.456.xyz/tunnel-files/frps || echo 不通)"
echo "== 完成 =="
