#!/usr/bin/env bash
# 生成 Termux 一键启动命令（无线主控 · 不经 Mac ADB）
# 用法: bash termux_agent_bootstrap.sh [device_id] [sdk_port]
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
DEVICE_ID="${1:-xgfe65eimrrofyws}"
SDK_PORT="${2:-8899}"
LAN_IP="$(ipconfig getifaddr en0 2>/dev/null || ipconfig getifaddr en1 2>/dev/null || echo "127.0.0.1")"
WS_URL="ws://${LAN_IP}:${SDK_PORT}/ws/device/${DEVICE_ID}"

# phantom Frida 端口（与 anti_detect/phantom_frida_config.json listen_port 一致）
FRIDA_PORT="17263"
if [[ -f "$ROOT/scripts/anti_detect/phantom_frida_config.json" ]]; then
  FRIDA_PORT="$(python3 -c "import json; print(json.load(open('$ROOT/scripts/anti_detect/phantom_frida_config.json'))['listen_port'])" 2>/dev/null || echo 17263)"
fi

echo "================================================================"
echo "  Termux Agent 启动命令（复制到红米 Termux）"
echo "  SDK: ${LAN_IP}:${SDK_PORT}  device: ${DEVICE_ID}"
echo "  Frida 本机端口: ${FRIDA_PORT}"
echo "================================================================"
echo ""
cat <<EOF
export WP_AGENT_ON_DEVICE=1
export WP_FRIDA_MODE=remote
export WP_FRIDA_PORT=${FRIDA_PORT}
export WP_AUTO_DISCOVER=1
export WP_SERVER_URL=${WS_URL}
cd ~/workphone/agent || cd ~/storage/downloads/workphone/agent
python agent.py -d ${DEVICE_ID} -s ${WS_URL} --heartbeat 10
# 或省略 -s，依赖 UDP 8898 自动发现（beacon 会广播 ${LAN_IP}）
EOF
echo ""
echo "验收（Mac）:"
echo "  curl http://${LAN_IP}:${SDK_PORT}/api/v3/connection/status | python3 -m json.tool"
echo "  curl http://${LAN_IP}:${SDK_PORT}/api/v3/hook/probe/${DEVICE_ID} | python3 -m json.tool"
