#!/usr/bin/env bash
# 守护：轮询微信 Frida 附着状态，一旦 frida_connected=true 立即跑真机验收（截图+读/发/转发+revoke）并退出。
# 真机铁律：只在 Frida 真附着时才跑 E2E，绝不伪造。
set -uo pipefail
SDK="${WORKPHONE_SDK_URL:-http://127.0.0.1:8899}"
DEVICE_ID="${DEVICE_ID:-xgfe65eimrrofyws}"
MAX_MIN="${MAX_MIN:-120}"        # 最长守护分钟
INTERVAL="${INTERVAL:-30}"
REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
LOG="$REPO_ROOT/sdk/tmp/auto_capture_$(date +%Y%m%d_%H%M%S).log"
mkdir -p "$(dirname "$LOG")"
deadline=$(( $(date +%s) + MAX_MIN*60 ))
echo "[watch] start sdk=$SDK device=$DEVICE_ID interval=${INTERVAL}s max=${MAX_MIN}min" | tee -a "$LOG"
while [ "$(date +%s)" -lt "$deadline" ]; do
  R="$(curl -sS -m 15 -X POST "$SDK/api/v3/wechat/execute" -H 'Content-Type: application/json' \
        -d "{\"device_id\":\"$DEVICE_ID\",\"action\":\"get_profile\",\"params\":{}}" 2>/dev/null)"
  FR="$(printf '%s' "$R" | python3 -c "import sys,json
try:
 d=json.load(sys.stdin);print((d.get('data') or {}).get('frida_connected'))
except: print('err')" 2>/dev/null)"
  echo "[watch] $(date +%H:%M:%S) frida_connected=$FR" | tee -a "$LOG"
  if [ "$FR" = "True" ]; then
    echo "[watch] Frida 已附着 → 跑真机验收" | tee -a "$LOG"
    WORKPHONE_SDK_URL="$SDK" DEVICE_ID="$DEVICE_ID" bash "$REPO_ROOT/sdk/scripts/run_wechat_realdevice_acceptance.sh" 2>&1 | tee -a "$LOG"
    echo "[watch] done exit=${PIPESTATUS[0]}" | tee -a "$LOG"
    exit 0
  fi
  sleep "$INTERVAL"
done
echo "[watch] 超时未等到 Frida 附着（${MAX_MIN}min），退出。设备侧需：微信前台+frida-server+Agent。" | tee -a "$LOG"
exit 2
