#!/system/bin/sh

echo "[*] 正在检测..."
echo "----------------------------------"
sleep 1

# 初始化结果变量
ROOT_CONFIRMED=false
HIDDEN_ROOT=false
DETECTED_ITEMS=()

# 检测函数封装（统一记录检测结果）
add_detection() {
    DETECTED_ITEMS+=("$1")
    ROOT_CONFIRMED=true
}

# 1. 基础文件检测
echo "[1/8] 基础文件扫描..."
if [ -f "/system/bin/su" ] || [ -f "/system/xbin/su" ] || [ -f "/sbin/su" ]; then
    add_detection "发现 su 二进制文件"
fi

# 2. Root 管理器扫描
echo "[2/8] Root 管理器深度扫描..."
ROOT_PATHS=(
    "/data/adb/magisk" "/data/adb/ksu" "/data/adb/apd"
    "/system/etc/init.d/99SuperSUDaemon" "/system/.magisk"
    "/data/magisk" "/dev/.magisk"
)
for path in "${ROOT_PATHS[@]}"; do
    if [ -e "$path" ]; then
        add_detection "发现 Root 管理器痕迹: $path"
    fi
done

# 3. 分区写入测试
echo "[3/8] 分区写入能力测试..."
TEST_FILES=("/system" "/vendor" "/data")
for dir in "${TEST_FILES[@]}"; do
    TEST_FILE="$dir/.test_$RANDOM"
    if touch $TEST_FILE 2>/dev/null; then
        rm -f $TEST_FILE
        add_detection "$dir 分区异常可写（应只读）"
    fi
done

# 4. 进程与环境分析
echo "[4/8] 进程与权限分析..."
if ps -A | grep -qE "magisk|zygisk|ksud|riru"; then
    add_detection "发现 Root 相关进程"
fi
if [ "$(id -u)" = "0" ]; then
    add_detection "当前会话具有 Root 权限"
fi

# 5. SELinux 与系统属性
echo "[5/8] 安全策略验证..."
if [ "$(getenforce)" = "Disabled" ]; then
    add_detection "SELinux 已禁用"
fi
if [ "$(getprop ro.secure)" = "0" ] || [ "$(getprop ro.debuggable)" = "1" ]; then
    add_detection "系统属性异常 (ro.secure=${getprop ro.secure}, ro.debuggable=${getprop ro.debuggable})"
fi

# 6. 动态行为检测
echo "[6/8] 动态行为监控..."
RESULT=$(timeout 2 su -c "echo test" 2>&1)
if echo "$RESULT" | grep -q "test"; then
    add_detection "隐蔽 Root 权限可用（su 命令响应成功）"
    HIDDEN_ROOT=true
elif echo "$RESULT" | grep -q "not found"; then
    echo "  [√] su 命令未找到"
else
    echo "  [?] su 命令返回异常: $RESULT"
fi

# 7. 硬件级验证
echo "[7/8] 硬件信任链检查..."
if [ "$(getprop ro.boot.verifiedbootstate)" != "green" ]; then
    add_detection "Bootloader 未锁定（状态: $(getprop ro.boot.verifiedbootstate)）"
fi
if dd if=/dev/block/by-name/boot 2>/dev/null | grep -q "magisk"; then
    add_detection "Boot 镜像被修改（Magisk/KSU 注入）"
fi

# 8. 内存特征扫描
echo "[8/8] 内存特征分析..."
if grep -q "magisk" /proc/self/maps 2>/dev/null; then
    add_detection "发现 Magisk 内存注入痕迹"
fi
if grep -q "riru" /proc/kallsyms 2>/dev/null; then
    add_detection "发现 Riru 内核符号"
fi

# 检测结果输出
echo ""
echo "======= 检测报告 ======="
if [ ${#DETECTED_ITEMS[@]} -gt 0 ]; then
    echo "[!] 发现 ${#DETECTED_ITEMS[@]} 个风险项:"
    for item in "${DETECTED_ITEMS[@]}"; do
        echo "  ● $item"
    done
    if $HIDDEN_ROOT; then
        echo "[!] 结论: 设备已 Root（高级隐藏）"
        echo "你这也不行啊，哈哈哈"
    else
        echo "[!] 结论: 设备已 Root"
    fi
else
    echo "[√] 未检测到 Root 痕迹"
fi
echo "----------------------------------"
