#!/usr/bin/env bash
# 在已 Root 的 USB 设备上安装并启动 frida-server 16.5.6（arm64/arm）
# 用法：在可访问 GitHub 的网络下执行
#   bash sdk/docs/install_frida_server_on_usb_device.sh
# 可选：SERIAL=xxxx bash sdk/docs/install_frida_server_on_usb_device.sh
set -euo pipefail
FRIDA_VER="16.5.6"
SERIAL="${SERIAL:-$(adb devices | awk '/\tdevice$/{print $1; exit}')}"
if [[ -z "$SERIAL" || "$SERIAL" == "List" ]]; then
  echo "未检测到已连接且 authorized 的设备，请插好 Type-C 并开启 USB 调试"
  exit 1
fi

echo ">>> 目标设备: $SERIAL"
ARCH=$(adb -s "$SERIAL" shell getprop ro.product.cpu.abi | tr -d '\r')
case "$ARCH" in
  arm64-v8a) FA="arm64" ;;
  armeabi-v7a) FA="arm" ;;
  x86_64) FA="x86_64" ;;
  x86) FA="x86" ;;
  *) echo "不支持的 ABI: $ARCH"; exit 1 ;;
esac
echo ">>> ABI: $ARCH -> frida android-$FA"

ROOT_CHECK=$(adb -s "$SERIAL" shell "su -c id" 2>/dev/null | tr -d '\r' || true)
if [[ "$ROOT_CHECK" != *"uid=0"* ]]; then
  echo "❌ 未检测到 Root（su 不可用）。请先完成 Magisk/Kitsune 等 Root 流程。"
  exit 1
fi
echo ">>> Root: OK ($ROOT_CHECK)"

TMP="/tmp/frida-server-${FRIDA_VER}-android-${FA}.xz"
URL="https://github.com/frida/frida/releases/download/${FRIDA_VER}/frida-server-${FRIDA_VER}-android-${FA}.xz"
echo ">>> 下载: $URL"
rm -f "$TMP" "${TMP%.xz}"
curl -fsSL --connect-timeout 20 --max-time 600 -C - -o "$TMP" "$URL"
xz -d -f "$TMP"
BIN="${TMP%.xz}"
ls -lh "$BIN"

REMOTE="/data/local/tmp/frida-server-16"
echo ">>> 推送 -> $REMOTE"
adb -s "$SERIAL" push "$BIN" "$REMOTE"
adb -s "$SERIAL" shell "su -c 'chmod 755 $REMOTE'"
adb -s "$SERIAL" shell "su -c 'killall frida-server 2>/dev/null; killall frida-server-16 2>/dev/null; true'"
adb -s "$SERIAL" shell "su -c 'nohup $REMOTE -D >/dev/null 2>&1 &'"
sleep 2
VPID=$(adb -s "$SERIAL" shell "su -c 'pidof frida-server-16'" | tr -d '\r')
if [[ -z "$VPID" ]]; then
  echo "❌ frida-server 未启动，请手动执行: adb shell su -c '$REMOTE -D'"
  exit 1
fi
echo ">>> frida-server 已运行 pid=$VPID"
adb -s "$SERIAL" shell "su -c '$REMOTE --version'" || true

if command -v frida-ps >/dev/null 2>&1; then
  echo ">>> 本机探测进程（前 5 行）:"
  frida-ps -U -D "$SERIAL" 2>/dev/null | head -5 || true
fi

echo ""
echo "✅ 完成。主机 Python 请保持: pip install 'frida==${FRIDA_VER}' 'frida-tools>=12.5,<13'"
