#!/usr/bin/env bash
# 奥创工作手机 · 真机清机（保留机擎 com.system.cloudservice + Magisk/Frida 基建）
# 真源 Skill：机擎/阿服/奥创真机清机/SKILL.md
# 用法：
#   bash sdk/scripts/clean_aochuang_device.sh [--dry-run|--apply] [-s SERIAL] [--deep]
# 默认 --dry-run；真清须显式 --apply

set -euo pipefail

SERIAL=""
MODE="dry-run"
DEEP=0
EVIDENCE_DIR=""
DEFAULT_SERIAL="xgfe65eimrrofyws"

# 奥创/S2 手机端包（资料真源：奥创微信控制接口与插件提取复用指南.md）
AOCHUANG_PACKAGES=(
  "org.xeslciw.manager"          # XESlciw Manager v1.8.4
  "top.zzz.vivwxjz"              # VivWxjz 微信 Hook
  "uni.UNI9421F6C"               # AI数智员工 / 007 业务入口
)

# 可能关联（--deep 才卸）
AOCHUANG_OPTIONAL_PACKAGES=(
  "io.github.vvb2060.mahoshojo"  # 魔法少女（资料提及同链路工具）
)

KEEP_PACKAGES=(
  "com.system.cloudservice"      # 机擎 Agent（禁止卸）
  "com.tencent.mm"               # 微信（默认保留数据）
)

# 框架/寄生目录（须 root）
AOCHUANG_ROOT_PATHS=(
  "/data/adb/xesd"
  "/data/adb/modules/xeslciw"
  "/data/adb/modules/XESlciw"
  "/data/adb/modules/grvjfe"
  "/data/adb/modules/vivwxjz"
)

# 常见残留 app 分区路径（资料：奥创工作手机-复刻开发详解.md §APK路径）
AOCHUANG_APP_DIRS=(
  "/data/app/manager_sign"
  "/data/app/VivWxjz"
  "/data/app/~~*org.xeslciw.manager*"
  "/data/app/~~*top.zzz.vivwxjz*"
  "/data/app/~~*uni.UNI9421F6C*"
)

usage() {
  cat <<'EOF'
奥创真机清机 — clean_aochuang_device.sh

  bash sdk/scripts/clean_aochuang_device.sh [选项]

选项：
  --dry-run     仅扫描+打印将执行的操作（默认）
  --apply       实际清理（须 ADB device + 建议 Root）
  -s SERIAL     设备序列号（默认唯一在线设备或 xgfe65eimrrofyws）
  --deep        额外卸 mahoshojo + 清 007 业务 app 数据目录
  --evidence DIR  留痕目录（默认 开发文档/8、部署/05-测试验收/YYYYMMDD_奥创清机_<serial>/）

保留（永不卸）：com.system.cloudservice、Magisk、机擎 Frida 基建
EOF
}

log() { printf '[%s] %s\n' "$(date '+%H:%M:%S')" "$*"; }
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 [[ -z "$su" ]]; then
    log "WARN: 无 su，跳过 root 操作: $cmd"
    return 1
  fi
  if [[ "$MODE" == "dry-run" ]]; then
    log "DRY su -c $(printf '%q' "$cmd")"
    return 0
  fi
  run_sh "$su -c $(printf '%q' "$cmd")" || return 1
}

pkg_installed() {
  local pkg="$1"
  run_sh pm path "$pkg" 2>/dev/null | grep -q .
}

do_uninstall_pkg() {
  local pkg="$1"
  if ! pkg_installed "$pkg"; then
    log "SKIP 未安装: $pkg"
    return 0
  fi
  if [[ "$MODE" == "dry-run" ]]; then
    log "DRY pm uninstall --user 0 $pkg"
    log "DRY pm uninstall $pkg"
    return 0
  fi
  log "卸载: $pkg"
  run_sh pm disable-user --user 0 "$pkg" 2>/dev/null || true
  run_sh am force-stop "$pkg" 2>/dev/null || true
  run_sh pm uninstall --user 0 "$pkg" 2>/dev/null || run_sh pm uninstall "$pkg" 2>/dev/null || log "WARN 卸载失败: $pkg"
}

clear_pkg_data() {
  local pkg="$1"
  if [[ "$MODE" == "dry-run" ]]; then
    log "DRY pm clear $pkg"
    return 0
  fi
  run_sh pm clear "$pkg" 2>/dev/null || true
}

remove_root_path() {
  local p="$1"
  if [[ "$MODE" == "dry-run" ]]; then
    log "DRY rm -rf $p"
    return 0
  fi
  run_root "rm -rf $(printf '%q' "$p")" || true
}

scan_magisk_modules() {
  log "== Magisk 模块扫描（名称含 xes/grvjfe/vivwx/lsposed 且非机擎） =="
  run_root 'ls -1 /data/adb/modules 2>/dev/null' | while read -r m; do
    [[ -z "$m" ]] && continue
    if echo "$m" | grep -qiE 'xes|grvjfe|vivwx|lsposed|edxposed|xposed'; then
      if echo "$m" | grep -qiE 'shamiko|zygisk|rezygisk|riru'; then
        log "KEEP Magisk模块(机擎基建): $m"
      else
        if [[ "$MODE" == "dry-run" ]]; then
          log "DRY 将禁用并移除模块: $m"
        else
          log "移除 Magisk 模块: $m"
          run_root "touch /data/adb/modules/$m/disable" || true
          run_root "rm -rf /data/adb/modules/$m" || true
        fi
      fi
    fi
  done || true
}

write_evidence() {
  [[ -z "$EVIDENCE_DIR" ]] && return 0
  mkdir -p "$EVIDENCE_DIR"
  {
    echo "# 奥创清机留痕 $(date '+%Y-%m-%d %H:%M:%S')"
    echo "serial=$SERIAL mode=$MODE deep=$DEEP"
    echo ""
    echo "## pm list packages (filter)"
    run_sh pm list packages 2>/dev/null | grep -iE 'xes|zzz|vivwx|UNI9421|mahoshojo|cloudservice' || true
    echo ""
    echo "## xesd"
    run_sh "ls -la /data/adb/xesd/ 2>/dev/null || echo NO_XESD" || true
  } >"$EVIDENCE_DIR/clean_report.txt"
  log "留痕: $EVIDENCE_DIR/clean_report.txt"
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --apply) MODE="apply" ;;
    --dry-run) MODE="dry-run" ;;
    -s) SERIAL="${2:-}"; shift ;;
    --deep) DEEP=1 ;;
    --evidence) EVIDENCE_DIR="${2:-}"; shift ;;
    -h|--help) usage; exit 0 ;;
    *) echo "未知参数: $1"; usage; exit 1 ;;
  esac
  shift
done

if [[ -z "$SERIAL" ]]; then
  SERIAL="$(adb devices 2>/dev/null | awk 'NR>1 && $2=="device" {print $1; exit}')"
  [[ -z "$SERIAL" ]] && SERIAL="$DEFAULT_SERIAL"
fi

if ! adb devices 2>/dev/null | awk -v s="$SERIAL" '$1==s && $2=="device" {found=1} END{exit !found}'; then
  echo "FAIL: 设备 $SERIAL 未在线（adb devices 无 device）"
  exit 1
fi

if [[ -z "$EVIDENCE_DIR" ]]; then
  EVIDENCE_DIR="$(cd "$(dirname "$0")/../.." && pwd)/开发文档/8、部署/05-测试验收/$(date '+%Y%m%d')_奥创清机_${SERIAL}"
fi

log "== 奥创真机清机 mode=$MODE serial=$SERIAL deep=$DEEP =="

for k in "${KEEP_PACKAGES[@]}"; do
  if pkg_installed "$k"; then
    log "KEEP 保留: $k"
  fi
done

log "== 1/6 停止并卸载奥创 APK =="
for pkg in "${AOCHUANG_PACKAGES[@]}"; do
  do_uninstall_pkg "$pkg"
done
if [[ "$DEEP" == "1" ]]; then
  for pkg in "${AOCHUANG_OPTIONAL_PACKAGES[@]}"; do
    do_uninstall_pkg "$pkg"
  done
fi

log "== 2/6 清理 app 数据（已卸包） =="
for pkg in "${AOCHUANG_PACKAGES[@]}"; do
  clear_pkg_data "$pkg"
done

log "== 3/6 移除框架目录 /data/adb/xesd 等 =="
for p in "${AOCHUANG_ROOT_PATHS[@]}"; do
  remove_root_path "$p"
done

log "== 4/6 Magisk 奥创相关模块 =="
scan_magisk_modules

log "== 5/6 残留分区路径 =="
for p in "${AOCHUANG_APP_DIRS[@]}"; do
  if [[ "$p" == *'*'* ]]; then
    if [[ "$MODE" == "dry-run" ]]; then
      log "DRY rm -rf $p"
    else
      run_root "rm -rf $p" 2>/dev/null || true
    fi
  else
    remove_root_path "$p"
  fi
done

log "== 6/6 重启提示 =="
if [[ "$MODE" == "apply" ]]; then
  log "建议: adb -s $SERIAL reboot（Magisk 模块变更后）"
fi

write_evidence

if [[ "$MODE" == "dry-run" ]]; then
  log "完成（dry-run）。真清请: bash sdk/scripts/clean_aochuang_device.sh --apply -s $SERIAL"
  log "验收: bash sdk/scripts/verify_aochuang_clean.sh -s $SERIAL"
else
  log "完成（apply）。请跑验收脚本确认全绿。"
fi
