#!/usr/bin/env bash
# 轮询等待 ADB 设备上线（USB 或无线），供 oneclick / 验收前使用
set -euo pipefail
SERIAL="${1:-192.168.110.80:5555}"
MAX_SEC="${2:-120}"
INTERVAL="${3:-3}"

echo "等待 ADB 设备: ${SERIAL}（最长 ${MAX_SEC}s）"
deadline=$((SECONDS + MAX_SEC))
while (( SECONDS < deadline )); do
  if [[ "$SERIAL" == *:* ]]; then
    adb connect "$SERIAL" >/dev/null 2>&1 || true
  fi
  state="$(adb -s "$SERIAL" get-state 2>/dev/null || true)"
  if [[ "$state" == "device" ]]; then
    echo "adb_ready $SERIAL"
    adb -s "$SERIAL" shell echo ok >/dev/null
    exit 0
  fi
  # 任意已授权 USB 设备
  any="$(adb devices | awk '/\tdevice$/{print $1; exit}')"
  if [[ -n "$any" ]]; then
    echo "adb_ready $any"
    exit 0
  fi
  sleep "$INTERVAL"
done
echo "adb_timeout $SERIAL" >&2
adb devices -l >&2 || true
exit 1
