#!/usr/bin/env bash
# 安装 Mac 常驻「连接守护」LaunchAgent（每 15s 扫描 ADB + 自动拉起 Termux Agent）
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.connection-keeper"
PLIST="${HOME}/Library/LaunchAgents/${LABEL}.plist"
LOG="${SDK_ROOT}/logs/connection_keeper.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/connection_keeper_daemon.sh</string>
  </array>
  <key>WorkingDirectory</key>
  <string>${PROJ_ROOT}</string>
  <key>EnvironmentVariables</key>
  <dict>
    <key>PATH</key>
    <string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
    <key>ANDROID_ADB_SERVER_PORT</key>
    <string>5038</string>
    <key>WORKPHONE_SDK_PORT</key>
    <string>8899</string>
    <key>KEEPER_INTERVAL</key>
    <string>15</string>
    <key>DEVICE_SERIAL</key>
    <string>192.168.110.80:5555</string>
    <key>DEVICE_ID</key>
    <string>xgfe65eimrrofyws</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/connection_keeper_daemon.sh" --bg

echo "✅ 连接守护 LaunchAgent 已安装: ${LABEL}"
echo "   日志: ${LOG}"
echo "   停止: bash ${SDK_ROOT}/scripts/connection_keeper_daemon.sh --stop"
