#!/usr/bin/env bash
# 运维兜底：ADB 一旦连上红米，自动在 Termux 启动 WS Agent（一次性 bootstrap，非日常主通道）
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LAN_ENV="${SCRIPT_DIR}/../config/lan.env"
if [[ -f "$LAN_ENV" ]]; then
  # shellcheck source=/dev/null
  source "$LAN_ENV"
fi
export ANDROID_ADB_SERVER_PORT="${ANDROID_ADB_SERVER_PORT:-5038}"
ADB=(adb -P "${ANDROID_ADB_SERVER_PORT}")
DEVICE_IP="${DEVICE_IP:-192.168.110.80:5555}"
DEVICE_ID="${DEVICE_ID:-xgfe65eimrrofyws}"
SDK_BASE="${WORKPHONE_API_URL:-http://127.0.0.1:8899}"
FRIDA_PORT="$(python3 -c "import json; print(json.load(open('${SCRIPT_DIR}/anti_detect/phantom_frida_config.json'))['listen_port'])" 2>/dev/null || echo 17263)"
WS_URL="${WORKPHONE_WS_URL:-ws://127.0.0.1:8899/ws/device/${DEVICE_ID}}"
LOG="/tmp/wp_adb_bootstrap_agent.log"
MAX_WAIT="${ADB_BOOTSTRAP_WAIT:-7200}"

exec >>"$LOG" 2>&1
echo "=== $(date) adb bootstrap agent wait ${DEVICE_IP} max=${MAX_WAIT}s ==="

deadline=$((SECONDS + MAX_WAIT))
while (( SECONDS < deadline )); do
  # 优先 USB 序列号，其次任意非 TV 的无线 device
  serial=""
  if [[ -n "${DEVICE_SERIAL:-}" ]] && "${ADB[@]}" -s "$DEVICE_SERIAL" get-state 2>/dev/null | grep -qx device; then
    serial="$DEVICE_SERIAL"
  else
    while IFS= read -r line; do
      s="${line%%$'\t'*}"
      [[ -z "$s" ]] && continue
      brand=$("${ADB[@]}" -s "$s" shell getprop ro.product.brand 2>/dev/null | tr -d '\r')
      [[ "$brand" == "haier" ]] && continue
      serial="$s"
      break
    done < <("${ADB[@]}" devices 2>/dev/null | awk '/\tdevice$/{print $1}')
  fi
  if [[ -n "$serial" ]]; then
    DEVICE_IP="$serial"
    echo "=== $(date) ADB ready serial=${serial}, bootstrap Termux Agent ==="
    "${ADB[@]}" -s "$serial" shell "am start -n com.termux/.HomeActivity" >/dev/null 2>&1 || true
    sleep 2
    CMD="export WP_AGENT_ON_DEVICE=1 WP_FRIDA_MODE=remote WP_FRIDA_PORT=${FRIDA_PORT}; cd ~/workphone/agent && python agent.py -d ${DEVICE_ID} -s ${WS_URL} --heartbeat 10"
    "${ADB[@]}" -s "$serial" shell am startservice -n com.termux/com.termux.app.RunCommandService \
      -a com.termux.RUN_COMMAND \
      --es com.termux.RUN_COMMAND_PATH /data/data/com.termux/files/usr/bin/bash \
      --esa com.termux.RUN_COMMAND_ARGUMENTS "-lc,${CMD}" 2>/dev/null || {
        echo "RunCommand 失败，请手动在 Termux 粘贴 termux_agent_bootstrap.sh 输出"
        bash "${SCRIPT_DIR}/termux_agent_bootstrap.sh" "$DEVICE_ID"
      }
    echo "=== bootstrap 已触发，等待 WS 上线 ==="
    bash "${SCRIPT_DIR}/wait_ws_agent.sh" "$DEVICE_ID" "$SDK_BASE" 120 5 && exit 0
  fi
  "${ADB[@]}" connect "${DEVICE_IP}" >/dev/null 2>&1 || true
  echo "  … $(date '+%H:%M:%S') waiting phone (skip haier TV)"
  sleep 10
done
echo "=== timeout ==="
exit 1
