#!/usr/bin/env bash
# 安装 / 卸载 macOS LaunchAgent：定时运行 docker_engine_guard.sh，降低「引擎假死 → 无鲸鱼/打不开」复发概率
#
# 安装：bash sdk/scripts/install_docker_engine_guard.sh
# 卸载：bash sdk/scripts/install_docker_engine_guard.sh --uninstall

set -euo pipefail

LABEL="com.workphone.docker-engine-guard"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
GUARD_SRC="${SCRIPT_DIR}/docker_engine_guard.sh"
# launchd 从「文稿」等目录执行脚本常被 TCC 拒绝，固定拷到 Application Support
INSTALL_DIR="${HOME}/Library/Application Support/com.workphone"
GUARD_SCRIPT="${INSTALL_DIR}/docker_engine_guard.sh"
PLIST_DST="${HOME}/Library/LaunchAgents/${LABEL}.plist"
LOG_OUT="${HOME}/Library/Logs/docker-engine-guard.log"
LOG_ERR="${HOME}/Library/Logs/docker-engine-guard.err.log"

if [[ "$(uname -s)" != "Darwin" ]]; then
  echo "仅支持 macOS。"
  exit 1
fi

if [[ ! -f "$GUARD_SRC" ]]; then
  echo "缺少: $GUARD_SRC"
  exit 1
fi
mkdir -p "$INSTALL_DIR"
cp -f "$GUARD_SRC" "$GUARD_SCRIPT"
chmod +x "$GUARD_SCRIPT"

if [[ "${1:-}" == "--uninstall" ]]; then
  launchctl bootout "gui/$(id -u)" "$PLIST_DST" 2>/dev/null || launchctl unload "$PLIST_DST" 2>/dev/null || true
  rm -f "$PLIST_DST"
  rm -f "$GUARD_SCRIPT" 2>/dev/null || true
  rmdir "${INSTALL_DIR}" 2>/dev/null || true
  echo "已卸载 LaunchAgent: $LABEL"
  exit 0
fi

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

# StartInterval：秒；600=每 10 分钟巡检一次（可按需改小/改大）
cat >"$PLIST_DST" <<PLIST
<?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>${GUARD_SCRIPT}</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>StartInterval</key>
  <integer>600</integer>
  <key>EnvironmentVariables</key>
  <dict>
    <key>PATH</key>
    <string>/opt/homebrew/bin:/usr/local/bin:${HOME}/.docker/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
  </dict>
  <key>StandardOutPath</key>
  <string>${LOG_OUT}</string>
  <key>StandardErrorPath</key>
  <string>${LOG_ERR}</string>
</dict>
</plist>
PLIST

launchctl bootout "gui/$(id -u)" "$PLIST_DST" 2>/dev/null || true
launchctl bootstrap "gui/$(id -u)" "$PLIST_DST" 2>/dev/null || launchctl load "$PLIST_DST"

echo "已安装并加载: $PLIST_DST"
echo "  周期: 每 10 分钟检查；日志: $LOG_OUT / $LOG_ERR"
echo "卸载: bash sdk/scripts/install_docker_engine_guard.sh --uninstall"
