#!/usr/bin/env bash
# 无线调试配对 + 连接（Android 11+ 无线调试需先 pair）
# 用法:
#   bash sdk/scripts/wireless_adb_pair.sh 192.168.1.12:37123 123456
#   PAIR_ADDR=192.168.1.12:37123 PAIR_CODE=123456 CONNECT_ADDR=192.168.1.12:5555 bash sdk/scripts/wireless_adb_pair.sh
set -euo pipefail
ADB_PORT="${ANDROID_ADB_SERVER_PORT:-5038}"
export ANDROID_ADB_SERVER_PORT="${ADB_PORT}"
ADB=(adb -P "${ADB_PORT}")

PAIR_ADDR="${1:-${PAIR_ADDR:-}}"
PAIR_CODE="${2:-${PAIR_CODE:-}}"
CONNECT_ADDR="${CONNECT_ADDR:-${PAIR_ADDR%:*}:5555}"

if [[ -z "$PAIR_ADDR" || -z "$PAIR_CODE" ]]; then
  echo "用法: $0 <IP:配对端口> <6位配对码>"
  echo "例:   $0 192.168.1.12:37123 482910"
  echo ""
  echo "手机路径: 设置 → 开发者选项 → 无线调试 → 使用配对码配对设备"
  exit 1
fi

echo "[pair] ${PAIR_ADDR} code=${PAIR_CODE}"
printf '%s\n' "$PAIR_CODE" | "${ADB[@]}" pair "$PAIR_ADDR"
sleep 2
echo "[connect] ${CONNECT_ADDR}"
"${ADB[@]}" connect "$CONNECT_ADDR"
sleep 2
"${ADB[@]}" devices -l
st=$("${ADB[@]}" -s "$CONNECT_ADDR" get-state 2>/dev/null || echo offline)
if [[ "$st" == "device" ]]; then
  echo "✅ 无线 ADB 就绪: ${CONNECT_ADDR}"
  brand=$("${ADB[@]}" -s "$CONNECT_ADDR" shell getprop ro.product.brand 2>/dev/null | tr -d '\r')
  model=$("${ADB[@]}" -s "$CONNECT_ADDR" shell getprop ro.product.model 2>/dev/null | tr -d '\r')
  echo "   brand=${brand} model=${model}"
  exit 0
fi
echo "❌ 状态: ${st}（若仍 offline 请重开无线调试或换 CONNECT_ADDR）"
exit 1
