#!/usr/bin/env bash
# 安装 LaunchAgent：Mac 开机/登录后自动建立 MindSpace 反向隧道
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
PLIST="$HOME/Library/LaunchAgents/cn.tkmind.memind-tunnel.plist"
TUNNEL="$ROOT/scripts/memind-mac-tunnel.sh"

chmod +x "$TUNNEL"

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>cn.tkmind.memind-tunnel</string>
  <key>ProgramArguments</key>
  <array>
    <string>${TUNNEL}</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>StandardOutPath</key>
  <string>${HOME}/Library/Logs/memind-mac-tunnel.log</string>
  <key>StandardErrorPath</key>
  <string>${HOME}/Library/Logs/memind-mac-tunnel.log</string>
</dict>
</plist>
EOF

launchctl bootout "gui/$(id -u)/cn.tkmind.memind-tunnel" 2>/dev/null || true
launchctl bootstrap "gui/$(id -u)" "$PLIST"
launchctl enable "gui/$(id -u)/cn.tkmind.memind-tunnel"
launchctl kickstart -k "gui/$(id -u)/cn.tkmind.memind-tunnel"

echo "已安装 MindSpace 反向隧道 LaunchAgent"
echo "日志: ~/Library/Logs/memind-mac-tunnel.log"
