#!/usr/bin/env bash
# 红米工作机：等 ADB → 升级微信(arm64) → oneclick 恢复 Frida
# 用法: bash upgrade_wechat_and_oneclick.sh [serial] [apk_path]
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SERIAL="${1:-xgfe65eimrrofyws}"
WIFI="192.168.110.80:5555"
APK_DIR="/tmp/wechat_apk"
LOG="${LOG:-/tmp/wp_reconnect_upgrade.log}"
PREFERRED_APK="${2:-${APK_DIR}/weixin8069_arm64.apk}"
FALLBACK_APK="${APK_DIR}/weixin8056_arm64.apk"
MAX_ROUNDS="${MAX_ROUNDS:-120}"

mkdir -p "$APK_DIR"
echo "=== $(date) upgrade_wechat_and_oneclick serial=$SERIAL ===" | tee "$LOG"

pick_apk() {
  if [[ -f "$PREFERRED_APK" ]] && [[ $(stat -f%z "$PREFERRED_APK" 2>/dev/null || stat -c%s "$PREFERRED_APK") -gt 50000000 ]]; then
    echo "$PREFERRED_APK"; return
  fi
  if [[ -f "$FALLBACK_APK" ]]; then echo "$FALLBACK_APK"; return; fi
  echo ""
}

resolve_dev() {
  adb connect "$WIFI" >/dev/null 2>&1 || true
  if adb devices 2>/dev/null | grep -q "${SERIAL}.*device"; then echo "$SERIAL"; return; fi
  if adb devices 2>/dev/null | grep -q "${WIFI}.*device"; then echo "$WIFI"; return; fi
  echo ""
}

for round in $(seq 1 "$MAX_ROUNDS"); do
  DEV="$(resolve_dev)"
  if [[ -n "$DEV" ]]; then
    echo "$(date) FOUND $DEV" | tee -a "$LOG"
    ABI=$(adb -s "$DEV" shell getprop ro.product.cpu.abi 2>/dev/null | tr -d '\r')
    OLD=$(adb -s "$DEV" shell dumpsys package com.tencent.mm 2>/dev/null | grep versionName | head -1 | tr -d '\r' || true)
    echo "ABI=$ABI OLD=$OLD" | tee -a "$LOG"
    APK="$(pick_apk)"
    if [[ -z "$APK" ]]; then
      echo "无可用 APK，请先下载到 $APK_DIR" | tee -a "$LOG"
      exit 2
    fi
    echo "install $APK -> $DEV" | tee -a "$LOG"
    adb -s "$DEV" install -r -d -t "$APK" 2>&1 | tee -a "$LOG" || true
    NEW=$(adb -s "$DEV" shell dumpsys package com.tencent.mm 2>/dev/null | grep versionName | head -1 | tr -d '\r' || true)
    echo "NEW=$NEW" | tee -a "$LOG"
    TARGET="$SERIAL"
    [[ "$DEV" == "$WIFI" ]] && TARGET="$DEV"
    bash "${SCRIPT_DIR}/frida_workphone_oneclick.sh" -d "$TARGET" 2>&1 | tee -a "$LOG" || true
    curl -s --max-time 20 "http://127.0.0.1:8899/api/v3/hook/probe/${SERIAL}" | tee -a "$LOG"
    echo "=== DONE $(date) ===" | tee -a "$LOG"
    exit 0
  fi
  echo "$(date) wait $round/$MAX_ROUNDS" >> "$LOG"
  sleep 5
done
echo "TIMEOUT: 未检测到 ADB，请插 Type-C 并授权 USB 调试" | tee -a "$LOG"
exit 1
