#!/bin/bash
# setup_frida.sh — 一键安装 Frida Server 到 Root Android 设备
#
# 用法：
#   ./scripts/setup_frida.sh [device_serial]
#
# 前置条件：
#   - 设备已 Root（Magisk）
#   - ADB 已连接且授权
#   - Python 已安装 frida-tools（pip install frida-tools）

set -e

DEVICE_ARG=""
if [ -n "$1" ]; then
    DEVICE_ARG="-s $1"
fi

echo "=== 机擎 SDK — Frida Server 安装脚本 ==="

# 1. 获取 Frida 版本（与 Python frida 包一致）
FRIDA_VERSION=$(python3 -c "import frida; print(frida.__version__)" 2>/dev/null)
if [ -z "$FRIDA_VERSION" ]; then
    echo "❌ Python frida 未安装，先执行: pip install frida-tools"
    exit 1
fi
echo "✅ 本机 Frida 版本: $FRIDA_VERSION"

# 2. 获取设备架构
ABI=$(adb $DEVICE_ARG shell getprop ro.product.cpu.abi)
echo "✅ 设备架构: $ABI"

case "$ABI" in
    arm64-v8a) ARCH="arm64" ;;
    armeabi-v7a) ARCH="arm" ;;
    x86_64) ARCH="x86_64" ;;
    x86) ARCH="x86" ;;
    *) echo "❌ 不支持的架构: $ABI"; exit 1 ;;
esac

# 3. 下载 frida-server
FILENAME="frida-server-${FRIDA_VERSION}-android-${ARCH}"
URL="https://github.com/frida/frida/releases/download/${FRIDA_VERSION}/${FILENAME}.xz"
TMPDIR="/tmp/frida_setup"
mkdir -p "$TMPDIR"

if [ ! -f "$TMPDIR/$FILENAME" ]; then
    echo "📥 下载 frida-server..."
    curl -L -o "$TMPDIR/${FILENAME}.xz" "$URL"
    xz -d "$TMPDIR/${FILENAME}.xz"
fi
echo "✅ frida-server 已就绪: $TMPDIR/$FILENAME"

# 4. 推送到设备
echo "📤 推送到设备 /data/local/tmp/frida-server ..."
adb $DEVICE_ARG push "$TMPDIR/$FILENAME" /data/local/tmp/frida-server
adb $DEVICE_ARG shell "su -c 'chmod 755 /data/local/tmp/frida-server'"
echo "✅ 已推送并赋权"

# 5. 启动 frida-server
echo "🚀 启动 frida-server ..."
adb $DEVICE_ARG shell "su -c 'pkill -f frida-server || true'" 2>/dev/null || true
adb $DEVICE_ARG shell "su -c 'nohup /data/local/tmp/frida-server >/dev/null 2>&1 &'" 
sleep 2

# 6. 验证
echo "🔍 验证连接..."
PONG=$(python3 -c "
import frida
try:
    d = frida.get_usb_device(timeout=5)
    print(f'✅ Frida 已连接设备: {d.name}')
    procs = len(d.enumerate_processes())
    print(f'✅ 检测到 {procs} 个进程')
except Exception as e:
    print(f'❌ 连接失败: {e}')
" 2>&1)
echo "$PONG"

echo ""
echo "=== 安装完成 ==="
echo "后续使用："
echo "  1. Agent 启动时会自动通过 FridaManager 连接"
echo "  2. 或手动测试: frida -U -n com.tencent.mm"
echo "  3. SDK 调用: POST /api/v3/message/send {\"channel\": \"hook\", ...}"
