#!/usr/bin/env bash
# ADB 连接稳定化：宿主机 adb server + USB/无线扫描 + u2/ATX + Agent/WS 自检
set -euo pipefail
SDK_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
SDK_PORT="${SDK_PORT:-8899}"
LAN_ENV="${SDK_ROOT}/config/lan.env"
if [[ -f "${LAN_ENV}" ]]; then
  # shellcheck source=/dev/null
  source "${LAN_ENV}" || true
fi
WIRELESS_IPS="${WIRELESS_IPS:-192.168.110.80 192.168.1.12 192.168.0.12}"
export ANDROID_ADB_SERVER_PORT="${ANDROID_ADB_SERVER_PORT:-5038}"
LOG="${TMPDIR:-/tmp}/adb-stabilize-$(date +%Y%m%d_%H%M%S).log"

adb() {
  command adb -P "${ANDROID_ADB_SERVER_PORT}" "$@"
}

exec > >(tee -a "$LOG") 2>&1
echo "=== ADB 连接稳定化 $(date) ==="
echo "日志: $LOG"
echo "ADB port: ${ANDROID_ADB_SERVER_PORT}"

bash "${SDK_ROOT}/scripts/adb_host_server_listen_all.sh" --background || true
sleep 1

echo "--- 清理离线无线连接 ---"
adb disconnect >/dev/null 2>&1 || true
adb kill-server >/dev/null 2>&1 || true
adb start-server >/dev/null 2>&1 || true
sleep 2

echo "--- USB / 已配对设备 ---"
adb devices -l || true

# 尝试无线（短超时，避免 hang）
for ip in $WIRELESS_IPS; do
  [[ "${ip}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] || continue
  ( adb connect "${ip}:5555" & pid=$!; sleep 3; kill $pid 2>/dev/null || true ) || true
done
adb devices -l || true

SERIAL=""
while read -r s st _rest; do
  [[ -z "${s}" || -z "${st}" ]] && continue
  if [[ "$st" == "device" ]]; then
    SERIAL="$s"
    break
  fi
  if [[ "$st" == "unauthorized" ]]; then
    echo "⚠️  设备 ${s} 未授权：请在手机上点「允许 USB 调试」并选「文件传输/MTP」"
  fi
done < <(adb devices | awk 'NR>1 && NF>=2 {print $1, $2}')

if [[ -z "$SERIAL" ]]; then
  echo "❌ 当前无已授权 ADB 设备"
  echo "   1) 开发者选项 → USB 调试 开启"
  echo "   2) USB 模式 → 文件传输"
  echo "   3) 重新插拔数据线，看手机弹窗点「允许」"
  echo "   4) 再运行: bash sdk/scripts/adb_connection_stabilize.sh"
  exit 1
fi

echo "✅ 已授权设备: $SERIAL"

if command -v python3 >/dev/null 2>&1; then
  echo "--- uiautomator2 init (ATX 9008) ---"
  python3 -m uiautomator2 init --serial "$SERIAL" 2>/dev/null || \
    python3 -m uiautomator2 init -s "$SERIAL" 2>/dev/null || \
    echo "⚠️  u2 init 跳过（可手动: python3 -m uiautomator2 init --serial $SERIAL）"
fi

echo "--- 启动 Frida 主控 + Agent ---"
bash "${SDK_ROOT}/scripts/frida_workphone_oneclick.sh" -d "$SERIAL" || true

echo "--- 连接状态 ---"
curl -s "http://127.0.0.1:${SDK_PORT}/api/v3/connection/status" | python3 -m json.tool 2>/dev/null || true
curl -s "http://127.0.0.1:${SDK_PORT}/api/v3/hook/probe/${SERIAL}" | python3 -m json.tool 2>/dev/null | head -20 || true

echo ""
echo "管理端: http://127.0.0.1:${SDK_PORT}/hub"
echo "设备控制台: http://127.0.0.1:${SDK_PORT}/static/index.html"
