#!/usr/bin/env bash
# JClaw Monitor · macOS LaunchAgent 自启 + 防 kill
# baicy day-2: "防止员工 kill JClaw Monitor"
#
# 装法：bash install-mac-launchagent.sh
# 卸载：bash install-mac-launchagent.sh --uninstall

set -euo pipefail

PLIST_NAME="com.ihousejapan.jclaw.monitor.plist"
LOCAL_PLIST="$(dirname "$0")/$PLIST_NAME"
TARGET_DIR="$HOME/Library/LaunchAgents"
TARGET_PLIST="$TARGET_DIR/$PLIST_NAME"
LABEL="com.ihousejapan.jclaw.monitor"

if [[ "${1:-}" == "--uninstall" ]]; then
  # Codex/CodeRabbit #443 三/四轮 P1：卸载必须 admin token 校验。
  #
  # 已知限制（baicy/iHouse 威胁模型内可接受）：
  #   - $JCLAW_DESKTOP_ADMIN_TOKEN 由当前 shell 控制，攻击者拿到 root/admin 后能
  #     自设这个 env 绕过。此 gating 防"普通员工 uninstall"，不是防真 root。
  #     真正 root 上锁需 SIP / DPAPI / TPM 介入，不在本 PR 范围。
  # CodeRabbit 四轮：token 改成 stdin 读，避免落进 shell history 和 ps 输出
  expected="${JCLAW_DESKTOP_ADMIN_TOKEN:-}"
  if [[ -z "$expected" ]]; then
    echo "❌ Cannot uninstall: env JCLAW_DESKTOP_ADMIN_TOKEN not set."
    echo "   ask admin (baicy) for the token, then:"
    echo "   JCLAW_DESKTOP_ADMIN_TOKEN=<token> bash $0 --uninstall"
    exit 2
  fi
  if [[ -t 0 ]]; then
    read -rs -p "Enter admin token: " given
    echo ""
  else
    read -r given
  fi
  if [[ -z "${given:-}" || "$given" != "$expected" ]]; then
    echo "❌ Cannot uninstall: token does not match."
    exit 2
  fi
  echo "Stopping + unloading $LABEL..."
  launchctl unload "$TARGET_PLIST" 2>/dev/null || true
  rm -f "$TARGET_PLIST"
  echo "✅ 已卸载。"
  exit 0
fi

# 校验 app 装在 /Applications
APP_PATH="/Applications/JClaw Monitor.app"
if [[ ! -d "$APP_PATH" ]]; then
  echo "❌ JClaw Monitor.app 不在 /Applications，先装好再跑这个脚本"
  exit 1
fi

# 校验源 plist 存在
if [[ ! -f "$LOCAL_PLIST" ]]; then
  echo "❌ 源 plist 模板不存在：$LOCAL_PLIST"
  exit 1
fi

mkdir -p "$TARGET_DIR"
mkdir -p "$HOME/Library/Logs"

# 把 plist 模板里的 __USERNAME__ 替换成实际用户名
# Codex/CodeRabbit #443：$USER 理论可能含 sed 特殊字符；用 # 当分隔符且把
# 特殊字符 escape 掉，防止生成损坏的 plist。macOS 用户名实测都是 [a-z0-9._-]，
# 但脚本本身不该 trust 这个。
USER_ESCAPED=$(printf '%s' "$USER" | sed -e 's/[\\&#]/\\&/g')
sed "s#__USERNAME__#${USER_ESCAPED}#g" "$LOCAL_PLIST" > "$TARGET_PLIST"
chmod 644 "$TARGET_PLIST"

# load + start
launchctl unload "$TARGET_PLIST" 2>/dev/null || true
launchctl load "$TARGET_PLIST"
launchctl start "$LABEL"

echo ""
echo "========================================"
echo "✅ macOS LaunchAgent 已装"
echo ""
echo "员工现在："
echo "  - 关机 / 注销重登 → 自动启动 JClaw Monitor"
echo "  - 强行 kill / Crash → 30 秒内自动重启"
echo ""
echo "日志位置："
echo "  $HOME/Library/Logs/JClawMonitor.out.log"
echo "  $HOME/Library/Logs/JClawMonitor.err.log"
echo ""
echo "卸载（管理员）：bash install-mac-launchagent.sh --uninstall"
echo "========================================"
