#!/usr/bin/env bash
# 无线主控一键 bootstrap：安装 SDK 监视器 + 生成手机 config +（有 ADB 时）OTA 推 Termux
# 用法: bash sdk/scripts/wireless_autoconnect_bootstrap.sh
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SDK_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
DEVICE_ID="${DEVICE_ID:-xgfe65eimrrofyws}"
EVID="${SDK_ROOT}/../开发文档/8、部署/05-测试验收/$(date +%Y%m%d)_无线主控bootstrap"

mkdir -p "$EVID"
echo "== 1/4 安装 Mac SDK 监视器（无 USB） =="
bash "${SCRIPT_DIR}/install_sdk_watcher_launchagent.sh"
bash "${SCRIPT_DIR}/sdk_connection_watcher.sh" --once | tee -a "${EVID}/watcher_once.log"

echo "== 2/4 生成手机 Agent config（NAS→Docker→frp） =="
python3 "${SCRIPT_DIR}/build_agent_config.py" --device-id "${DEVICE_ID}" --for-phone --out "${EVID}/agent_config.json"
cp "${EVID}/agent_config.json" "${SDK_ROOT}/config/agent_config_${DEVICE_ID}.json"

echo "== 3/4 OTA 推手机（需 ADB 一次，之后可无 USB） =="
serial=$(adb devices 2>/dev/null | awk '/\tdevice$/{print $1; exit}')
if [[ -n "$serial" ]]; then
  DEVICE_SERIAL="$serial" DEVICE_ID="$DEVICE_ID" \
    bash "${SCRIPT_DIR}/termux_push_and_start_agent.sh" | tee -a "${EVID}/termux_push.log"
else
  echo "SKIP OTA: 无 ADB。请手机 Termux 手动复制 ${EVID}/agent_config.json → ~/workphone/agent/config.json 后运行 start_agent.sh"
fi

echo "== 4/4 验收 =="
source "${SDK_ROOT}/config/active_sdk.env" 2>/dev/null || true
echo "WORKPHONE_SDK_URL=${WORKPHONE_SDK_URL:-unset}"
curl -sf --max-time 5 "${WORKPHONE_SDK_URL:-http://127.0.0.1:8899}/api/v3/connection/status" | \
  python3 -c "import sys,json;d=json.load(sys.stdin)['data'];print('ws',d.get('online_ws_count'),'ids',d.get('online_device_ids'))"
echo "证据目录: ${EVID}"
