#!/usr/bin/env bash
# ==================================================================
# AF9 — Phantom-Frida / StrongR-Frida 自动部署脚本
#
# 功能：
#   1. 检测设备 CPU 架构
#   2. 下载对应的反检测 Frida Server 二进制
#   3. 推送到设备 /data/local/tmp/，随机命名（反扫描）
#   4. 启动时使用随机端口（避免 27042 默认端口检测）
#
# 用法：
#   bash setup_phantom_frida.sh [device_serial]
#
# 依赖：adb, curl/wget, unxz
# ==================================================================

set -euo pipefail

DEVICE_SERIAL="${1:-}"
ADB_CMD="adb"
[ -n "$DEVICE_SERIAL" ] && ADB_CMD="adb -s $DEVICE_SERIAL"

FRIDA_VERSION="${FRIDA_VERSION:-16.6.6}"
PHANTOM_REPO="https://github.com/aspect-dev/phantom-frida/releases/download"
STRONGR_REPO="https://github.com/aspect-dev/strongr-frida/releases/download"

if command -v shuf >/dev/null 2>&1; then
  RAND_PORT=$(shuf -i 10000-60000 -n 1)
else
  RAND_PORT=$((10000 + RANDOM % 50001))
fi
RAND_NAME="fs_$(head -c 6 /dev/urandom | xxd -p)"

echo "=== Phantom-Frida 部署脚本 ==="
echo "Frida版本: $FRIDA_VERSION"
echo "随机端口: $RAND_PORT"
echo "服务名称: $RAND_NAME"

# Step 1: 检测 CPU 架构
ARCH=$($ADB_CMD shell getprop ro.product.cpu.abi | tr -d '\r')
echo "设备架构: $ARCH"

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

BINARY_NAME="frida-server-${FRIDA_VERSION}-android-${FRIDA_ARCH}"
DOWNLOAD_URL="${PHANTOM_REPO}/${FRIDA_VERSION}/${BINARY_NAME}.xz"
FALLBACK_URL="${STRONGR_REPO}/${FRIDA_VERSION}/${BINARY_NAME}.xz"

TMPDIR=$(mktemp -d)
trap "rm -rf $TMPDIR" EXIT

echo "下载 Phantom-Frida..."
if ! curl -L -f -o "$TMPDIR/${BINARY_NAME}.xz" "$DOWNLOAD_URL" 2>/dev/null; then
  echo "Phantom-Frida 下载失败，尝试 StrongR-Frida..."
  if ! curl -L -f -o "$TMPDIR/${BINARY_NAME}.xz" "$FALLBACK_URL" 2>/dev/null; then
    echo "=== 自动下载失败 ==="
    echo "请手动下载以下任一版本："
    echo "  Phantom-Frida: https://github.com/aspect-dev/phantom-frida/releases"
    echo "  StrongR-Frida: https://github.com/aspect-dev/strongr-frida/releases"
    echo "下载后放到 $TMPDIR/${BINARY_NAME}.xz 再重新执行"
    exit 1
  fi
fi

echo "解压..."
unxz "$TMPDIR/${BINARY_NAME}.xz"

echo "推送到设备..."
$ADB_CMD push "$TMPDIR/${BINARY_NAME}" "/data/local/tmp/${RAND_NAME}"
$ADB_CMD shell "chmod 755 /data/local/tmp/${RAND_NAME}"

echo "停止旧 Frida 进程..."
$ADB_CMD shell "su -c 'pkill -f frida-server'" 2>/dev/null || true
$ADB_CMD shell "su -c 'pkill -f hluda-server'" 2>/dev/null || true
sleep 1

echo "启动 Phantom-Frida（端口=$RAND_PORT）..."
$ADB_CMD shell "su -c 'nohup /data/local/tmp/${RAND_NAME} -l 0.0.0.0:${RAND_PORT} &'" &
sleep 2

RUNNING=$($ADB_CMD shell "ps | grep ${RAND_NAME}" | wc -l || echo "0")
if [ "$RUNNING" -gt 0 ]; then
  echo "=== 部署成功 ==="
  echo "名称: $RAND_NAME"
  echo "端口: $RAND_PORT"
  echo "路径: /data/local/tmp/${RAND_NAME}"
  echo ""
  echo "连接方式: frida -H 127.0.0.1:${RAND_PORT} -n com.tencent.mm"
  echo "ADB转发: adb forward tcp:${RAND_PORT} tcp:${RAND_PORT}"

  CONFIG_FILE="$(dirname "$0")/phantom_frida_config.json"
  cat > "$CONFIG_FILE" <<EOJSON
{
  "device_serial": "${DEVICE_SERIAL:-auto}",
  "frida_version": "${FRIDA_VERSION}",
  "binary_name": "${RAND_NAME}",
  "binary_path": "/data/local/tmp/${RAND_NAME}",
  "listen_port": ${RAND_PORT},
  "arch": "${FRIDA_ARCH}",
  "deployed_at": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
}
EOJSON
  echo "配置已保存: $CONFIG_FILE"
else
  echo "=== 启动失败，请检查 Root 权限 ==="
  exit 1
fi
