#!/bin/bash
# RemoteSys macOS 一键安装脚本
# 用法（终端里一行搞定）:
#   curl -fsSL http://remote.51hmkj.cn/agent/install_mac.sh | bash
# 或下载后执行:
#   bash install_mac.sh
set -u

SERVER="${RS_SERVER:-http://remote.51hmkj.cn}"
DIR="$HOME/RemoteSys"
FILES="agent.py agent_gui.py rs_unlock.py"

C_G='\033[1;32m'; C_R='\033[1;31m'; C_Y='\033[1;33m'; C_0='\033[0m'
ok()   { printf "${C_G}[✓]${C_0} %s\n" "$1"; }
warn() { printf "${C_Y}[!]${C_0} %s\n" "$1"; }
fail() { printf "${C_R}[✗]${C_0} %s\n" "$1"; exit 1; }

echo ""
echo "========================================"
echo "  RemoteSys 远程协助 · macOS 安装向导"
echo "========================================"
echo ""

# ---------- 1. Python3 ----------
PY=""
for c in python3 /usr/bin/python3 /opt/homebrew/bin/python3 /usr/local/bin/python3; do
  if command -v "$c" >/dev/null 2>&1; then PY="$c"; break; fi
done
if [ -z "$PY" ]; then
  echo "未检测到 python3，正在唤起 Apple 命令行工具安装（会弹窗，点『安装』）…"
  xcode-select --install 2>/dev/null
  fail "装完命令行工具后（约 5 分钟），重新运行本命令即可继续。"
fi
ok "Python: $($PY --version 2>&1) ($PY)"

# ---------- 2. tkinter（GUI 需要） ----------
if ! "$PY" -c "import tkinter" >/dev/null 2>&1; then
  warn "当前 Python 缺少 tkinter 图形组件，尝试用 Homebrew 补齐…"
  if command -v brew >/dev/null 2>&1; then
    brew install --quiet python-tk@3.13 2>/dev/null || brew install --quiet python-tk || true
  fi
  if ! "$PY" -c "import tkinter" >/dev/null 2>&1; then
    warn "tkinter 仍不可用：将只安装后台服务（可用网页远程，但本机不显示 GUI 窗口）。"
    warn "如需 GUI：安装 Homebrew 后执行  brew install python-tk  再重跑本脚本。"
  fi
fi

# ---------- 3. pip 依赖 ----------
echo "正在安装依赖（mss / Pillow / websockets / pynput）…"
PIPARGS="--user --quiet --no-warn-script-location"
"$PY" -m pip install $PIPARGS mss Pillow websockets pynput >/dev/null 2>&1 \
  || "$PY" -m pip install --user --quiet --break-system-packages mss Pillow websockets pynput >/dev/null 2>&1 \
  || fail "依赖安装失败，请手动执行: $PY -m pip install --user mss Pillow websockets pynput"
ok "依赖安装完成"

# ---------- 4. 下载客户端 ----------
mkdir -p "$DIR"
for f in $FILES; do
  curl -fsSL "$SERVER/agent/$f" -o "$DIR/$f" || fail "下载 $f 失败，请检查网络"
done
ok "客户端文件已就绪: $DIR"

# ---------- 5. 桌面启动器 ----------
DESK="$HOME/Desktop"
[ -d "$DESK" ] || DESK="$DIR"
cat > "$DESK/RemoteSys.command" <<EOF
#!/bin/bash
cd "$DIR"
exec "$PY" "$DIR/agent_gui.py"
EOF
chmod +x "$DESK/RemoteSys.command"
ok "已创建桌面启动器: RemoteSys.command（双击即开）"

# ---------- 6. 开机自启 ----------
PLIST="$HOME/Library/LaunchAgents/cn.51hmkj.remotesys.plist"
mkdir -p "$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>cn.51hmkj.remotesys</string>
  <key>ProgramArguments</key><array>
    <string>$PY</string><string>$DIR/agent_gui.py</string>
  </array>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><false/>
</dict></plist>
EOF
launchctl unload "$PLIST" >/dev/null 2>&1
launchctl load "$PLIST" >/dev/null 2>&1 && ok "已注册开机自启（下次登录自动运行）" \
  || warn "开机自启注册失败，可手动双击桌面启动器"

# ---------- 7. 系统权限提示 ----------
"$PY" -c "import tkinter" >/dev/null 2>&1 && "$DESK/RemoteSys.command" >/dev/null 2>&1 </dev/null &
echo ""
ok "安装完成！接下来："
echo "    1. 在弹出的 RemoteSys 窗口登录你的账号"
echo "    2. 首次使用需授权：系统设置 → 隐私与安全性 →"
echo "       「屏幕录制」和「辅助功能」里勾选 Python/Terminal"
echo ""
read -p "现在打开系统权限设置页？[Y/n] " ans </dev/tty 2>/dev/null || ans="y"
case "$ans" in
  n|N*) ;;
  *) open "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture" ;;
esac
