#!/usr/bin/env bash
# 确保 WebSocket Agent + Phantom Frida 在线（存客宝对接口径：WS+Frida，非 ADB UI）
#
# ⚠️ 无线主控请改用 ensure_ws_agent_wireless.sh — 本脚本在 Mac 运行，依赖 ADB forward。
set -euo pipefail
SDK_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
DEVICE_SERIAL="${DEVICE_SERIAL:-192.168.110.80:5555}"
SDK_PORT="${SDK_PORT:-8899}"
PH_CFG="${SDK_ROOT}/scripts/anti_detect/phantom_frida_config.json"
PH_KEEPALIVE="${SDK_ROOT}/scripts/phantom_frida_keepalive.sh"
LOG="/tmp/wp_agent_ws.log"

if [[ ! -f "$PH_CFG" ]]; then
  echo "缺少 phantom 配置，先运行: bash scripts/frida_workphone_oneclick.sh -d ${DEVICE_SERIAL}"
  exit 1
fi

PH_PORT=$(python3 -c "import json; print(json.load(open('${PH_CFG}'))['listen_port'])")
# 只允许一个读同一 phantom 配置的保活器，避免 Frida 重启后回到默认/随机端口。
if ! pgrep -f "${PH_KEEPALIVE} ${DEVICE_SERIAL}" >/dev/null 2>&1; then
  nohup bash "${PH_KEEPALIVE}" "${DEVICE_SERIAL}" \
    >> /tmp/phantom_frida_keepalive.log 2>&1 &
fi
adb -s "${DEVICE_SERIAL}" forward "tcp:${PH_PORT}" "tcp:${PH_PORT}" >/dev/null 2>&1 || true

pkill -f "agent.py -d ${DEVICE_SERIAL} -s ws://127.0.0.1:${SDK_PORT}" 2>/dev/null || true
sleep 1

# Frida attach 需要微信进程
WX_PID="$(adb -s "${DEVICE_SERIAL}" shell pidof com.tencent.mm 2>/dev/null | tr -d '\r' || true)"
if [[ -z "${WX_PID}" ]]; then
  echo "拉起微信..."
  adb -s "${DEVICE_SERIAL}" shell am start -n com.tencent.mm/.ui.LauncherUI >/dev/null 2>&1 || true
  sleep 6
fi

cd "${SDK_ROOT}/agent"
export WP_FRIDA_MODE=remote
export WP_DEVICE_SERIAL="${DEVICE_SERIAL}"
export WP_FRIDA_PORT="${PH_PORT}"
nohup python3 agent.py \
  -d "${DEVICE_SERIAL}" \
  -s "ws://127.0.0.1:${SDK_PORT}/ws/device" \
  --heartbeat 10 >> "${LOG}" 2>&1 &
echo "Agent pid=$! device=${DEVICE_SERIAL} frida_port=${PH_PORT}"
for _i in $(seq 1 20); do
  if grep -q "RPC ping: pong" "${LOG}" 2>/dev/null; then
    echo "frida_rpc_ready"
    break
  fi
  sleep 2
done
curl -s "http://127.0.0.1:${SDK_PORT}/api/v3/connection/status" | python3 -c "
import sys,json
d=json.load(sys.stdin).get('data',{})
print('ws_online', d.get('online_ws_count'), d.get('online_device_ids'))
"
