#!/usr/bin/env bash
# 安装 g2.tkmind.cn 50/50 负载均衡：Caddy :8090 + SSH 隧道 + 更新 cloudflared
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
TUNNEL="$ROOT/scripts/g2-h5-tunnel.sh"
CADDYFILE="$ROOT/scripts/g2-lb.Caddyfile"
CF_CONFIG="/Users/john/Project/ollama/cloudflare/config.yml"
TUNNEL_PLIST="$HOME/Library/LaunchAgents/cn.tkmind.g2-h5-tunnel.plist"
LB_PLIST="$HOME/Library/LaunchAgents/cn.tkmind.g2-lb.plist"
LOG_DIR="$HOME/Library/Logs"

chmod +x "$TUNNEL" "$(dirname "$0")/install-g2-lb.sh"
mkdir -p "$LOG_DIR"

cat >"$TUNNEL_PLIST" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>cn.tkmind.g2-h5-tunnel</string>
  <key>ProgramArguments</key>
  <array>
    <string>${TUNNEL}</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>StandardOutPath</key>
  <string>${LOG_DIR}/g2-h5-tunnel.log</string>
  <key>StandardErrorPath</key>
  <string>${LOG_DIR}/g2-h5-tunnel.log</string>
</dict>
</plist>
EOF

cat >"$LB_PLIST" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>cn.tkmind.g2-lb</string>
  <key>ProgramArguments</key>
  <array>
    <string>/opt/homebrew/bin/caddy</string>
    <string>run</string>
    <string>--config</string>
    <string>${CADDYFILE}</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>StandardOutPath</key>
  <string>${LOG_DIR}/g2-lb.log</string>
  <key>StandardErrorPath</key>
  <string>${LOG_DIR}/g2-lb.log</string>
</dict>
</plist>
EOF

if grep -q '127.0.0.1:8090' "$CF_CONFIG"; then
  echo "cloudflared 已指向 :8090，跳过 config 修改"
else
  sed -i '' 's|service: http://127.0.0.1:8081|service: http://127.0.0.1:8090|' "$CF_CONFIG"
  echo "已更新 $CF_CONFIG → g2 指向 :8090"
fi

UID_NUM="$(id -u)"
GUI="gui/${UID_NUM}"

launchctl bootout "$GUI/cn.tkmind.g2-h5-tunnel" 2>/dev/null || true
launchctl bootstrap "$GUI" "$TUNNEL_PLIST"
launchctl enable "$GUI/cn.tkmind.g2-h5-tunnel"
launchctl kickstart -k "$GUI/cn.tkmind.g2-h5-tunnel"

launchctl bootout "$GUI/cn.tkmind.g2-lb" 2>/dev/null || true
launchctl bootstrap "$GUI" "$LB_PLIST"
launchctl enable "$GUI/cn.tkmind.g2-lb"
launchctl kickstart -k "$GUI/cn.tkmind.g2-lb"

launchctl kickstart -k "$GUI/com.cloudflare.cloudflared"

sleep 2
echo ""
echo "=== g2 负载均衡状态 ==="
curl -s -o /dev/null -w "本机 upstream :8081  → %{http_code}\n" http://127.0.0.1:8081/api/status || true
curl -s -o /dev/null -w "105  upstream :18080 → %{http_code}\n" http://127.0.0.1:18080/api/status || true
curl -s -o /dev/null -w "Caddy LB      :8090 → %{http_code}\n" http://127.0.0.1:8090/api/status || true
echo ""
echo "日志: ~/Library/Logs/g2-h5-tunnel.log ~/Library/Logs/g2-lb.log"
echo "外网验证: curl -sI https://m.tkmind.cn/api/status"
