#!/usr/bin/env bash
# 重启/断线后自动等待 ADB → oneclick → 验收 WS 在线
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SDK_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
DEVICE_SERIAL="${DEVICE_SERIAL:-192.168.110.80:5555}"
SDK_PORT="${WORKPHONE_SDK_PORT:-8899}"
INTERVAL="${INTERVAL:-10}"
LOG="${SDK_ROOT}/logs/auto_recover.log"
mkdir -p "${SDK_ROOT}/logs"

log() { echo "[$(date '+%F %T')] $*" | tee -a "$LOG"; }

try_wireless_debug_ports() {
  local host="${DEVICE_SERIAL%%:*}"
  (
    local p open_port=""
    for p in $(seq 37000 37200); do
      if nc -z -G 1 "$host" "$p" 2>/dev/null; then
        open_port="$p"
        break
      fi
    done
    if [[ -n "$open_port" ]]; then
      log "wireless_debug_port=${host}:${open_port} → adb connect"
      try_adb_connect "${host}:${open_port}"
    fi
  ) &
}

try_usb_device() {
  local any
  any="$(adb devices | awk '/\tdevice$/{print $1; exit}')"
  if [[ -n "$any" && "$any" != "$DEVICE_SERIAL" ]]; then
    log "usb_device_found=${any}"
    DEVICE_SERIAL="$any"
  fi
}

try_adb_connect() {
  local target="$1"
  [[ "$target" != *:* ]] && return 0
  adb connect "$target" >/dev/null 2>&1 &
  local pid=$!
  local waited=0
  while kill -0 "$pid" 2>/dev/null && (( waited < 3 )); do
    sleep 1
    waited=$((waited + 1))
  done
  if kill -0 "$pid" 2>/dev/null; then
    kill "$pid" 2>/dev/null || true
    wait "$pid" 2>/dev/null || true
  else
    wait "$pid" 2>/dev/null || true
  fi
}

log "auto_recover start device=${DEVICE_SERIAL} interval=${INTERVAL}s"
cycle=0

while true; do
  cycle=$((cycle + 1))
  try_usb_device
  if [[ "$DEVICE_SERIAL" == *:* ]]; then
    try_adb_connect "$DEVICE_SERIAL"
  fi
  if (( cycle % 6 == 0 )); then
    try_wireless_debug_ports
  fi
  state="$(adb -s "$DEVICE_SERIAL" get-state 2>/dev/null || true)"
  if [[ "$state" != "device" ]]; then
    any="$(adb devices | awk '/\tdevice$/{print $1; exit}')"
    if [[ -n "$any" ]]; then
      DEVICE_SERIAL="$any"
      state="$(adb -s "$DEVICE_SERIAL" get-state 2>/dev/null || true)"
    fi
  fi
  if [[ "$state" == "device" ]]; then
    log "adb online serial=${DEVICE_SERIAL} → running oneclick"
    if DEVICE_SERIAL="$DEVICE_SERIAL" bash "${SCRIPT_DIR}/frida_workphone_oneclick.sh" >>"$LOG" 2>&1; then
      ws="$(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(d.get('online_ws_count',0))" 2>/dev/null || echo 0)"
      log "oneclick done ws_online=${ws}"
      if [[ "$ws" -ge 1 ]]; then
        log "auto_recover success"
        exit 0
      fi
    fi
    log "oneclick incomplete, retry in ${INTERVAL}s"
  else
    host="${DEVICE_SERIAL%%:*}"
    if ping -c 1 -W 2 "$host" >/dev/null 2>&1; then
      log "waiting adb (${state:-offline}) phone_ping=ok → 开「无线调试」或 USB 连一次 adb tcpip 5555"
    else
      log "waiting adb (${state:-offline}) phone_ping=fail"
    fi
  fi
  sleep "$INTERVAL"
done
