#!/usr/bin/env bash
# 交互式辅助：创建 Cloudflare Tunnel 并绑定 w.tkmind.cn
# 需已安装 cloudflared 且可访问 Cloudflare 账号
set -e

HOSTNAME="${WORDLOOP_HOSTNAME:-w.tkmind.cn}"
TUNNEL_NAME="${WORDLOOP_TUNNEL_NAME:-wordloop}"
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
CF_DIR="$ROOT/deploy/cloudflared"

if ! command -v cloudflared >/dev/null 2>&1; then
  echo "请先安装 cloudflared: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/"
  exit 1
fi

mkdir -p "$CF_DIR"

echo ">>> 1/4 登录 Cloudflare（将打开浏览器）..."
cloudflared tunnel login

echo ">>> 2/4 创建隧道: $TUNNEL_NAME"
cloudflared tunnel create "$TUNNEL_NAME" || true

CRED=$(ls -1 "$HOME/.cloudflared"/*.json 2>/dev/null | head -1)
if [ -z "$CRED" ]; then
  echo "未找到 credentials JSON，请检查 ~/.cloudflared/"
  exit 1
fi

CONFIG="$CF_DIR/config.yml"
if [ ! -f "$CONFIG" ]; then
  sed -e "s|/path/to/.cloudflared/<TUNNEL-UUID>.json|$CRED|" \
      -e "s|hostname: w.tkmind.cn|hostname: $HOSTNAME|" \
      "$CF_DIR/config.yml.example" > "$CONFIG"
  echo "已生成 $CONFIG"
else
  echo "保留已有 $CONFIG"
fi

echo ">>> 3/4 DNS: $HOSTNAME -> 隧道 $TUNNEL_NAME"
cloudflared tunnel route dns "$TUNNEL_NAME" "$HOSTNAME"

echo ">>> 4/4 请先确保 Nginx 在 127.0.0.1:8080 提供 WordLoop，然后运行："
echo "    cloudflared tunnel --config $CONFIG run"
echo ""
echo "生产环境可复制 systemd 单元：deploy/systemd/cloudflared-wordloop.service"
