#!/usr/bin/env bash
# ==================================================================
# AF10 — Root 隐藏模块自动安装脚本
#
# 安装顺序（针对 Magisk/KernelSU 设备）：
#   1. Shamiko (Magisk Zygisk) 或 KernelSU 自带隐藏
#   2. HMA-OSS (Hide My Applist) — 隐藏应用列表
#   3. Play Integrity Fork — 通过 Play Integrity 检测
#   4. TrickStore — 签名欺骗
#
# 本脚本提供模板和检查流程，实际需要在已 Root 的真机上执行。
#
# 用法：
#   bash setup_root_hide.sh [device_serial]
# ==================================================================

set -euo pipefail

DEVICE_SERIAL="${1:-}"
ADB_CMD="adb"
[ -n "$DEVICE_SERIAL" ] && ADB_CMD="adb -s $DEVICE_SERIAL"

echo "=== Root 隐藏模块部署脚本 ==="

check_root_method() {
  if $ADB_CMD shell "su -c 'magisk -v'" 2>/dev/null | grep -q "magisk"; then
    echo "magisk"
  elif $ADB_CMD shell "su -c 'ksud --version'" 2>/dev/null | grep -q "kernelsu\|ksu"; then
    echo "kernelsu"
  elif $ADB_CMD shell "su -c 'apd --version'" 2>/dev/null | grep -q "apatch"; then
    echo "apatch"
  else
    echo "unknown"
  fi
}

ROOT_METHOD=$(check_root_method)
echo "Root方案: $ROOT_METHOD"

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
MODULES_DIR="$SCRIPT_DIR/root_modules"
mkdir -p "$MODULES_DIR"

# Shamiko
SHAMIKO_URL="https://github.com/aspect-dev/Shamiko/releases/latest/download/Shamiko.zip"
SHAMIKO_ZIP="$MODULES_DIR/Shamiko.zip"

# HMA-OSS (Hide My Applist)
HMA_URL="https://github.com/aspect-dev/HMA-OSS/releases/latest/download/HMA-OSS.zip"
HMA_ZIP="$MODULES_DIR/HMA-OSS.zip"

# Play Integrity Fork
PIF_URL="https://github.com/aspect-dev/PlayIntegrityFork/releases/latest/download/PlayIntegrityFork.zip"
PIF_ZIP="$MODULES_DIR/PlayIntegrityFork.zip"

download_if_missing() {
  local url="$1" dest="$2" name="$3"
  if [ -f "$dest" ]; then
    echo "[$name] 已缓存: $dest"
  else
    echo "[$name] 下载中..."
    if curl -L -f -o "$dest" "$url" 2>/dev/null; then
      echo "[$name] 下载完成"
    else
      echo "[$name] 下载失败，请手动下载: $url"
      echo "         放到: $dest"
    fi
  fi
}

install_magisk_module() {
  local zip_path="$1" name="$2"
  if [ ! -f "$zip_path" ]; then
    echo "[$name] 模块文件不存在，跳过"
    return
  fi
  echo "[$name] 推送到设备..."
  $ADB_CMD push "$zip_path" "/data/local/tmp/$(basename "$zip_path")"
  echo "[$name] 安装..."
  $ADB_CMD shell "su -c 'magisk --install-module /data/local/tmp/$(basename "$zip_path")'" 2>/dev/null || \
    echo "[$name] 自动安装失败。请手动在 Magisk App 中安装: /data/local/tmp/$(basename "$zip_path")"
}

echo ""
echo "=== Step 1: 下载模块 ==="
download_if_missing "$SHAMIKO_URL" "$SHAMIKO_ZIP" "Shamiko"
download_if_missing "$HMA_URL" "$HMA_ZIP" "HMA-OSS"
download_if_missing "$PIF_URL" "$PIF_ZIP" "PlayIntegrityFork"

echo ""
echo "=== Step 2: 安装模块 ==="

if [ "$ROOT_METHOD" = "magisk" ]; then
  echo "检测到 Magisk，确保 Zygisk 已开启..."
  ZYGISK=$($ADB_CMD shell "su -c 'magisk --sqlite \"SELECT value FROM settings WHERE key=\\\"zygisk\\\"\"'" 2>/dev/null || echo "")
  if echo "$ZYGISK" | grep -q "1"; then
    echo "Zygisk 已启用"
  else
    echo "⚠ Zygisk 未启用。请在 Magisk App 设置中开启 Zygisk 后重启设备"
  fi

  install_magisk_module "$SHAMIKO_ZIP" "Shamiko"
  install_magisk_module "$HMA_ZIP" "HMA-OSS"
  install_magisk_module "$PIF_ZIP" "PlayIntegrityFork"

elif [ "$ROOT_METHOD" = "kernelsu" ]; then
  echo "KernelSU 模式，推送模块到 /data/local/tmp/..."
  [ -f "$HMA_ZIP" ] && $ADB_CMD push "$HMA_ZIP" "/data/local/tmp/HMA-OSS.zip"
  [ -f "$PIF_ZIP" ] && $ADB_CMD push "$PIF_ZIP" "/data/local/tmp/PlayIntegrityFork.zip"
  echo "请在 KernelSU Manager 中手动安装以上模块"

else
  echo "未检测到已知 Root 方案，请确保设备已 Root"
  echo "模块已下载到: $MODULES_DIR/"
  echo "请手动安装"
fi

echo ""
echo "=== Step 3: 配置排除列表 ==="
HIDE_APPS=(
  "com.tencent.mm"
  "com.tencent.xin"
  "com.ss.android.ugc.aweme"
  "com.xingin.xhs"
  "com.taobao.idlefish"
)
echo "以下应用应加入排除/隐藏列表："
for app in "${HIDE_APPS[@]}"; do
  echo "  - $app"
done
echo ""
echo "Shamiko: 在 Magisk 排除列表(DenyList)中勾选以上应用"
echo "HMA-OSS: 在 HMA 配置中启用对以上应用的应用列表隐藏"

echo ""
echo "=== Step 4: 验证 ==="
echo "验证命令（在设备上执行）："
echo "  su -c 'ls /system/xbin/su'           # 应隐藏"
echo "  su -c 'which magisk'                  # 应隐藏"
echo "  pm list packages | grep magisk        # 应无结果"
echo "  pm list packages | grep supersu       # 应无结果"
echo ""

REPORT_FILE="$SCRIPT_DIR/root_hide_report.json"
cat > "$REPORT_FILE" <<EOJSON
{
  "device_serial": "${DEVICE_SERIAL:-auto}",
  "root_method": "${ROOT_METHOD}",
  "modules_downloaded": {
    "shamiko": $([ -f "$SHAMIKO_ZIP" ] && echo "true" || echo "false"),
    "hma_oss": $([ -f "$HMA_ZIP" ] && echo "true" || echo "false"),
    "play_integrity_fork": $([ -f "$PIF_ZIP" ] && echo "true" || echo "false")
  },
  "hide_apps": $(printf '%s\n' "${HIDE_APPS[@]}" | jq -R . | jq -s .),
  "deployed_at": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
}
EOJSON
echo "报告已保存: $REPORT_FILE"
echo ""
echo "=== 完成（重启设备后生效） ==="
echo "执行: $ADB_CMD reboot"
