#!/usr/bin/env bash
# 安装 Mac 常驻「SDK 连接监视器」（无 USB 铁律 · 只盯 NAS/frp/WS）
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SDK_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
PROJ_ROOT="$(cd "${SDK_ROOT}/.." && pwd)"
LABEL="com.karuo.workphone.sdk-watcher"
PLIST="${HOME}/Library/LaunchAgents/${LABEL}.plist"
LOG="${SDK_ROOT}/logs/sdk_connection_watcher.log"

mkdir -p "${SDK_ROOT}/logs" "${HOME}/Library/LaunchAgents"

cat > "${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>${LABEL}</string>
  <key>ProgramArguments</key>
  <array>
    <string>/bin/bash</string>
    <string>${SDK_ROOT}/scripts/sdk_connection_watcher.sh</string>
  </array>
  <key>WorkingDirectory</key>
  <string>${PROJ_ROOT}</string>
  <key>EnvironmentVariables</key>
  <dict>
    <key>WORKPHONE_SDK_PORT</key>
    <string>8899</string>
    <key>DEVICE_ID</key>
    <string>xgfe65eimrrofyws</string>
    <key>WATCHER_INTERVAL</key>
    <string>20</string>
  </dict>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>StandardOutPath</key>
  <string>${LOG}</string>
  <key>StandardErrorPath</key>
  <string>${LOG}</string>
</dict>
</plist>
EOF

launchctl bootout "gui/$(id -u)/${LABEL}" 2>/dev/null || true
launchctl bootstrap "gui/$(id -u)" "${PLIST}"
launchctl enable "gui/$(id -u)/${LABEL}"
launchctl kickstart -k "gui/$(id -u)/${LABEL}" 2>/dev/null || \
  bash "${SDK_ROOT}/scripts/sdk_connection_watcher.sh" --bg

echo "✅ SDK 监视器 LaunchAgent 已安装: ${LABEL}"
echo "   日志: ${LOG}"
echo "   当前 SDK: source ${SDK_ROOT}/config/active_sdk.env"
