#!/usr/bin/env bash
# 一键安装「按需 TTS」：nginx 反代 + systemd 常驻自启
# 用法： sudo bash /var/www/tingxie/install_tts.sh
set -euo pipefail

SRV=/var/www/tingxie
NGINX_BIN=/usr/sbin/nginx
NGINX_SITE=/etc/nginx/sites-enabled/tingxie.ai-memo.cn
SYSTEMD_UNIT=/etc/systemd/system/tingxie-tts.service

echo "==> [1/5] 停止已运行的 tts_server（释放 8899）"
pkill -f "tts_server.py" 2>/dev/null || true
sleep 1

echo "==> [2/5] 安装 systemd 单元并启动"
cp "$SRV/tingxie-tts.service" "$SYSTEMD_UNIT"
systemctl daemon-reload
systemctl enable tingxie-tts
systemctl restart tingxie-tts
systemctl status tingxie-tts --no-pager || true

echo "==> [3/5] 注入 nginx /tts 反代（幂等）"
if ! grep -q "location /tts" "$NGINX_SITE"; then
  cp "$NGINX_SITE" "${NGINX_SITE}.bak.$(date +%s)"
  python3 - "$NGINX_SITE" "$SRV/nginx_tts_location.conf" <<'PY'
import sys
site, snippet = sys.argv[1], sys.argv[2]
with open(snippet) as f:
    block = f.read()
with open(site) as f:
    content = f.read()
if "location /tts" not in content:
    marker = "location / {"
    idx = content.find(marker)
    if idx != -1:
        content = content[:idx] + block + "\n\n" + content[idx:]
    else:
        content = content.rstrip() + "\n\n" + block + "\n"
    with open(site, "w") as f:
        f.write(content)
PY
  echo "    已写入 /tts 反代"
else
  echo "    /tts 已存在，跳过"
fi

echo "==> [4/5] 校验并 reload nginx"
"$NGINX_BIN" -t
systemctl reload nginx 2>/dev/null || "$NGINX_BIN" -s reload 2>/dev/null || true

echo "==> [5/5] 验证可达性"
sleep 1
curl -s -o /dev/null -w "    本地 8899 : HTTP=%{http_code}\n" "http://127.0.0.1:8899/tts?text=%E5%8C%BA%E5%9D%97%E9%93%BE"
curl -s -o /dev/null -w "    外部域名 : HTTP=%{http_code}\n" "http://tingxie.ai-memo.cn/tts?text=%E5%8C%BA%E5%9D%97%E9%93%BE"
echo "完成。"
