#!/usr/bin/env bash
# 奥创清机验收门禁 — exit 0 = 无奥创残留；exit 1 = 仍有残留
# 真源：机擎/阿服/奥创真机清机/SKILL.md

set -euo pipefail

SERIAL=""
DEFAULT_SERIAL="xgfe65eimrrofyws"
EVIDENCE_DIR=""
FAIL=0

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

while [[ $# -gt 0 ]]; do
  case "$1" in
    -s) SERIAL="${2:-}"; shift ;;
    --evidence) EVIDENCE_DIR="${2:-}"; shift ;;
    -h|--help)
      echo "用法: bash sdk/scripts/verify_aochuang_clean.sh [-s SERIAL] [--evidence DIR]"
      exit 0
      ;;
    *) echo "未知参数: $1"; 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

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

check() {
  local name="$1"
  local ok="$2"
  if [[ "$ok" == "1" ]]; then
    echo "OK  $name"
  else
    echo "FAIL $name"
    FAIL=1
  fi
}

echo "== 奥创清机验收 serial=$SERIAL =="

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

# 1. 核心包
for pkg in "${AOCHUANG_PACKAGES[@]}"; do
  if adb_sh pm path "$pkg" 2>/dev/null | grep -q .; then
    check "包未卸: $pkg" 0
  else
    check "包已卸: $pkg" 1
  fi
done

# 2. xesd 框架目录
if adb_sh "test -d /data/adb/xesd && echo YES || echo NO" 2>/dev/null | grep -q YES; then
  check "/data/adb/xesd 仍存在" 0
else
  check "/data/adb/xesd 不存在" 1
fi

# 3. 机擎 Agent 必须保留
if adb_sh pm path com.system.cloudservice 2>/dev/null | grep -q .; then
  check "机擎 Agent 保留: com.system.cloudservice" 1
else
  check "机擎 Agent 缺失: com.system.cloudservice" 0
fi

# 4. 可疑 Magisk 模块名
bad_mods=""
bad_mods="$(adb_sh 'su -c "ls /data/adb/modules 2>/dev/null"' 2>/dev/null | grep -iE 'xes|grvjfe|vivwx' || true)"
if [[ -n "$bad_mods" ]]; then
  check "Magisk奥创模块: $bad_mods" 0
else
  check "无 Magisk 奥创模块名" 1
fi

# 5. pm 模糊扫描
leaks="$(adb_sh pm list packages 2>/dev/null | grep -iE 'xes|vivwx|UNI9421F6C' || true)"
if [[ -n "$leaks" ]]; then
  check "pm 模糊残留: $leaks" 0
else
  check "pm 无奥创模糊匹配" 1
fi

if [[ -n "$EVIDENCE_DIR" ]]; then
  mkdir -p "$EVIDENCE_DIR"
  {
    echo "serial=$SERIAL fail=$FAIL"
    adb_sh pm list packages 2>/dev/null | grep -iE 'xes|zzz|vivwx|UNI9421|cloudservice' || true
    adb_sh "ls -la /data/adb/xesd/ 2>/dev/null || echo NO_XESD"
  } >"$EVIDENCE_DIR/verify_report.txt"
fi

if [[ "$FAIL" == "0" ]]; then
  echo "PASS: 奥创清机验收全绿"
  exit 0
fi
echo "FAIL: 仍有奥创残留，请 bash sdk/scripts/clean_aochuang_device.sh --apply -s $SERIAL"
exit 1
