#!/usr/bin/env bash
# 奥创工作手机 · 真机全量提取到 资料/奥创工作手机APK提取/
# 真源：资料/奥创微信控制接口与插件提取复用指南.md · 机擎/阿服/奥创真机清机/SKILL.md
#
# 用法：
#   bash sdk/scripts/extract_aochuang_to_ziliao.sh [-s SERIAL] [--decompile]
#
# 前置：Type-C USB 调试 + adb devices 见 device（或无线 adb connect）

set -euo pipefail

ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
OUT="${ROOT}/资料/奥创工作手机APK提取"
EVID="${ROOT}/开发文档/8、部署/05-测试验收/$(date +%Y%m%d)_奥创资料提取_$(date +%H%M%S)"
SERIAL=""
DECOMPILE=0
DEFAULT_SERIAL="xgfe65eimrrofyws"

AOCHUANG_PACKAGES=(
  "org.xeslciw.manager"
  "top.zzz.vivwxjz"
  "uni.UNI9421F6C"
)

AOCHUANG_ROOT_PATHS=(
  "/data/adb/xesd"
  "/data/adb/modules"
)

log() { printf '[%s] %s\n' "$(date '+%H:%M:%S')" "$*"; }

usage() {
  cat <<'EOF'
奥创真机全量提取 → 资料/奥创工作手机APK提取/

  bash sdk/scripts/extract_aochuang_to_ziliao.sh [-s SERIAL] [--decompile]

  --decompile   额外 apktool 反编译到 decompiled/<包名>/
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    -s) SERIAL="$2"; shift 2 ;;
    --decompile) DECOMPILE=1; shift ;;
    -h|--help) usage; exit 0 ;;
    *) echo "未知参数: $1"; usage; exit 1 ;;
  esac
done

pick_serial() {
  if [[ -n "$SERIAL" ]]; then return; fi
  local online
  online="$(adb devices | awk '/\tdevice$/{print $1; exit}')"
  if [[ -n "$online" ]]; then SERIAL="$online"; return; fi
  if adb devices | grep -q "^${DEFAULT_SERIAL}[[:space:]]"; then
    SERIAL="$DEFAULT_SERIAL"
  fi
}

run_adb() { adb -s "$SERIAL" "$@"; }
run_sh() { run_adb shell "$@"; }

pick_su() {
  run_sh 'for p in /sbin/su /system/bin/su /system/xbin/su su; do
    if [ -x "$p" ] 2>/dev/null || command -v "$p" >/dev/null 2>&1; then echo "$p"; exit 0; fi
  done; exit 1' 2>/dev/null || true
}

run_root() {
  local cmd="$1"
  local su
  su="$(pick_su)"
  if [[ -n "$su" ]]; then
    run_sh "su -c $(printf '%q' "$cmd")" 2>/dev/null
  else
    run_sh "$cmd" 2>/dev/null || true
  fi
}

pick_serial
if [[ -z "$SERIAL" ]] || ! adb devices | grep -q "^${SERIAL}[[:space:]]*device"; then
  echo "FAIL: 无 ADB 在线设备。请 Type-C 连接并开启 USB 调试，或 adb connect <ip>:5555"
  adb devices -l
  exit 1
fi

mkdir -p "$OUT" "$EVID"
log "serial=$SERIAL out=$OUT"

# --- 设备画像 ---
{
  echo "# 奥创提取 · 设备检查 $(date '+%Y-%m-%d %H:%M:%S')"
  echo
  adb devices -l
  echo
  run_adb shell getprop ro.product.model
  run_adb shell getprop ro.build.version.release
  run_adb shell getprop ro.product.brand
} > "$EVID/00_device_info.txt"

run_sh pm list packages > "$EVID/01_all_packages.txt" 2>/dev/null || true
grep -E 'xes|zzz|vivwx|UNI9421|cloudservice|magisk|tencent\.mm' "$EVID/01_all_packages.txt" > "$EVID/02_aochuang_related_packages.txt" 2>/dev/null || true

# --- 拉 APK ---
for pkg in "${AOCHUANG_PACKAGES[@]}"; do
  apk_path="$(run_sh pm path "$pkg" 2>/dev/null | head -1 | cut -d: -f2 | tr -d '\r' || true)"
  if [[ -z "$apk_path" ]]; then
    log "SKIP APK 未安装: $pkg"
    echo "NOT_INSTALLED $pkg" >> "$EVID/03_apk_pull.log"
    continue
  fi
  ver="$(run_sh dumpsys package "$pkg" 2>/dev/null | awk -F= '/versionName/{print $2; exit}' | tr -d '\r ')"
  safe="${pkg}_v${ver:-unknown}.apk"
  log "PULL $pkg -> $safe"
  run_adb pull "$apk_path" "$OUT/$safe"
  echo "OK $pkg $apk_path -> $OUT/$safe" >> "$EVID/03_apk_pull.log"
done

# --- 框架 / Magisk 模块（需 root）---
for p in "${AOCHUANG_ROOT_PATHS[@]}"; do
  dest="$OUT/device_root$(echo "$p" | tr '/' '_')"
  log "TAR $p (root)"
  run_root "test -e '$p' && tar -czf /sdcard/aochuang_extract_$(basename "$p").tgz '$p' 2>/dev/null" || true
  tgz="/sdcard/aochuang_extract_$(basename "$p").tgz"
  if run_sh "test -f '$tgz'" 2>/dev/null | grep -q .; then
    mkdir -p "$dest"
    run_adb pull "$tgz" "$dest/" 2>/dev/null || true
    run_root "rm -f '$tgz'" || true
  else
    echo "MISSING_OR_DENIED $p" >> "$EVID/04_root_paths.log"
  fi
done

# Magisk 模块名过滤
run_root 'ls /data/adb/modules 2>/dev/null' > "$EVID/05_magisk_modules.txt" 2>/dev/null || true

# --- 可选反编译 ---
if [[ "$DECOMPILE" -eq 1 ]] && command -v apktool >/dev/null 2>&1; then
  DEC="$OUT/decompiled"
  mkdir -p "$DEC"
  for apk in "$OUT"/*.apk; do
    [[ -f "$apk" ]] || continue
    base="$(basename "$apk" .apk)"
    log "apktool d $base"
    apktool d -f -o "$DEC/$base" "$apk" >> "$EVID/06_apktool.log" 2>&1 || true
  done
fi

log "DONE 证据目录: $EVID"
log "资料目录: $OUT"
ls -lah "$OUT"
