#!/usr/bin/env bash
# 宿主机 ADB server 监听所有网卡，供 Docker 内通过 ADB_SERVER_SOCKET=tcp:host.docker.internal:5038 连接。
# 见：机擎/references/ADB_Docker_USB排查.md
set -euo pipefail
ADB_PORT="${ANDROID_ADB_SERVER_PORT:-5038}"
export ANDROID_ADB_SERVER_PORT="${ADB_PORT}"
ADB=(adb -P "${ADB_PORT}")
LOG="${ADB_HOST_SERVER_LOG:-${TMPDIR:-/tmp}/adb-host-server-${ADB_PORT}.log}"

case "${1:-}" in
  --background)
    "${ADB[@]}" kill-server 2>/dev/null || true
    # -a：允许非本机连接（Docker 网桥访问宿主机 ADB 端口）
    nohup "${ADB[@]}" -a nodaemon server >>"$LOG" 2>&1 &
    echo "adb host server PID $! port=${ADB_PORT} (log: $LOG)"
    sleep 1
    "${ADB[@]}" devices -l || true
    ;;
  *)
    "${ADB[@]}" kill-server 2>/dev/null || true
    exec "${ADB[@]}" -a nodaemon server
    ;;
esac
