#!/system/bin/sh
RED='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[1;33m'
BLUE='\033[1;34m'
PURPLE='\033[1;35m'
CYAN='\033[1;36m'
WHITE='\033[1;37m'
NC='\033[0m'
show_separator() {
    echo "=============================================="
}
show_title() {
    clear
    echo "=============================================="
    echo "  Hacker手机工具箱1.1"
    echo "  作者：Hacker\n  作者TG：@liuhua8\n  此手机功能脚本无毒无害无需root，后续会更新跟多功能，均无毒无害，大家放心使用\n  Hacker"
    echo "=============================================="
    echo
}
get_all_phone_info() {
    echo "${BLUE}Hacker${NC}"
    show_separator
    
    echo "${WHITE}【基础设备信息】${NC}"
    if [ -x "$(command -v getprop)" ]; then
        MODEL=$(getprop ro.product.model 2>/dev/null || echo "未知")
        MANUFACTURER=$(getprop ro.product.manufacturer 2>/dev/null || echo "未知")
        BRAND=$(getprop ro.product.brand 2>/dev/null || echo "未知")
        DEVICE=$(getprop ro.product.device 2>/dev/null || echo "未知")
        echo "型号: $MODEL"
        echo "制造商: $MANUFACTURER"
        echo "品牌: $BRAND"
        echo "设备: $DEVICE"
    else
        echo "无法获取设备属性信息"
    fi
    echo -e "\n${WHITE}【CPU与系统信息】${NC}"
    ARCH=$(uname -m 2>/dev/null || echo "未知")
    ANDROID_VER=$(getprop ro.build.version.release 2>/dev/null || echo "未知")
    SDK_VER=$(getprop ro.build.version.sdk 2>/dev/null || echo "未知")
    SECURITY_PATCH=$(getprop ro.build.version.security_patch 2>/dev/null || echo "未知")
    echo "CPU架构: $ARCH"
    echo "Android版本: $ANDROID_VER"
    echo "SDK版本: $SDK_VER"
    echo "安全补丁: $SECURITY_PATCH"
    echo -e "\n${WHITE}【内存信息】${NC}"
    if [ -f /proc/meminfo ]; then
        TOTAL_MEM_KB=$(grep "MemTotal" /proc/meminfo | awk '{print $2}')
        AVAIL_MEM_KB=$(grep "MemAvailable" /proc/meminfo | awk '{print $2}')
        TOTAL_MEM=$(expr "$TOTAL_MEM_KB" / 1024)
        AVAIL_MEM=$(expr "$AVAIL_MEM_KB" / 1024)
        USED_MEM=$(expr "$TOTAL_MEM" - "$AVAIL_MEM")
        MEM_USAGE_PERCENT=$((USED_MEM * 100 / TOTAL_MEM))
        echo "总运行内存: ${TOTAL_MEM}MB"
        echo "可用运行内存: ${AVAIL_MEM}MB"
        echo "内存使用率: ${MEM_USAGE_PERCENT}%"
    else
        echo "无法获取内存信息"
    fi
    echo -e "\n${WHITE}【存储信息】${NC}"
    if [ -x "$(command -v df)" ]; then
        echo "存储分区使用情况:"
        df -h 2>/dev/null | grep -E "/data|/sdcard|/system|/cache" | while read line; do
            echo "  $line"
        done
    else
        echo "无法获取存储信息"
    fi
    echo -e "\n${WHITE}【电池信息】${NC}"
    BATTERY_CAPACITY=$(cat /sys/class/power_supply/battery/capacity 2>/dev/null || echo "未知")
    BATTERY_STATUS=$(cat /sys/class/power_supply/battery/status 2>/dev/null || echo "未知")
    echo "电池电量: ${BATTERY_CAPACITY}%"
    echo "充电状态: ${BATTERY_STATUS}"
    show_separator
    echo
}
clean_storage() {
    echo "${YELLOW}Hacker${NC}"
    show_separator
    
    CLEAN_FOLDERS=(
        "/sdcard/Recycling" "/sdcard/Recycle Bin"
        "/sdcard/Backup" "/data/backup"
        "/sdcard/Temp" "/data/local/tmp"
        "/sdcard/Log" "/data/log"
        "/sdcard/DCIM/.thumbnails" "/sdcard/Pictures/.thumbnails"
        "/sdcard/Download"
        "/data/data/*/cache" "/sdcard/Android/data/*/cache"
    )
    echo "即将清理以下类型文件夹："
    echo "- 回收站、备份文件、临时文件、系统日志"
    echo "- 图片缩略图、下载文件、应用缓存"
    echo -e "\n${RED}注意：清理后部分文件无法恢复，请确认！${NC}"
    echo -n "是否继续清理？(输入'是'确认，其他取消): "
    read CONFIRM
    if [ "$CONFIRM" != "是" ]; then
        echo "${GREEN}已取消清理操作${NC}"
        show_separator
        echo
        return
    fi
    echo -e "\n开始清理...\n"
    CLEAN_COUNT=0
    TOTAL_CLEANED_SIZE=0
    for FOLDER in "${CLEAN_FOLDERS[@]}"; do
        if [ -d "$FOLDER" ]; then
            echo "正在清理: $FOLDER"
            FOLDER_SIZE=$(du -sk "$FOLDER" 2>/dev/null | awk '{print $1}')
            find "$FOLDER" -type f -delete 2>/dev/null
            if [ $? -eq 0 ]; then
                echo "  ✅ 清理完成 (释放: ${FOLDER_SIZE}KB)"
                CLEAN_COUNT=$(expr "$CLEAN_COUNT" + 1)
                TOTAL_CLEANED_SIZE=$(expr "$TOTAL_CLEANED_SIZE" + "$FOLDER_SIZE")
            else
                echo "  ❌ 清理失败（权限不足或目录异常）"
            fi
        fi
    done
    TOTAL_CLEANED_MB=$(expr "$TOTAL_CLEANED_SIZE" / 1024)
    echo -e "\n${GREEN}清理完成！共处理 ${CLEAN_COUNT} 个文件夹，释放约 ${TOTAL_CLEANED_MB}MB 空间${NC}"
    show_separator
    echo
}
get_daily_quote() {
    echo "${PURPLE}Hacker${NC}"
    show_separator
    
    if [ ! -x "$(command -v curl)" ] && [ ! -x "$(command -v wget)" ]; then
        echo "${RED}错误：系统缺少curl或wget，无法调用接口${NC}"
        show_separator
        echo
        return
    fi
    echo "正在获取今日语录...\n"
    if [ -x "$(command -v curl)" ]; then
        QUOTE_DATA=$(curl -s --connect-timeout 10 "https://v.api.aa1.cn/api/yiyan/index.php" 2>/dev/null)
    else
        QUOTE_DATA=$(wget -q -T 10 -O - "https://v.api.aa1.cn/api/yiyan/index.php" 2>/dev/null)
    fi
    if [ -z "$QUOTE_DATA" ] || [ "$QUOTE_DATA" = "error" ]; then
        echo "${RED}获取失败：网络异常或接口暂时不可用${NC}"
        echo "备用语录：生活就像海洋，只有意志坚强的人才能到达彼岸。"
    else
        echo "${WHITE}今日一言：${NC}"
        echo "  $QUOTE_DATA"
    fi
    show_separator
    echo
}
check_virus_threats() {
    local mode=$1
    echo -e "\n${WHITE}【病毒与恶意软件检测】${NC}"
    
    if [ "$mode" = "root" ] && [ $(id -u) -eq 0 ]; then
        echo "${RED}ROOT模式深度病毒扫描${NC}"
        
        # 系统关键目录扫描
        echo "🔍 扫描系统关键目录..."
        SUSPICIOUS_SYSTEM_FILES=0
        SYSTEM_SCAN_PATHS=("/system/app" "/system/priv-app" "/system/vendor/app" "/system/xbin")
        
        for path in "${SYSTEM_SCAN_PATHS[@]}"; do
            if [ -d "$path" ]; then
                file_count=$(find "$path" -type f \( -name "*.apk" -o -name "*.dex" -o -name "*.so" \) 2>/dev/null | wc -l)
                echo "  $path: $file_count 个可执行文件"
                SUSPICIOUS_SYSTEM_FILES=$(expr "$SUSPICIOUS_SYSTEM_FILES" + "$file_count")
            fi
        done
        
        # 启动项检查
        echo "🔍 检查系统启动项..."
        if [ -d "/system/etc/init.d" ]; then
            init_scripts=$(find /system/etc/init.d -type f 2>/dev/null | wc -l)
            echo "  初始化脚本: $init_scripts 个"
        fi
        
        if [ $SUSPICIOUS_SYSTEM_FILES -gt 100 ]; then
            echo "${RED}⚠️  发现较多系统可执行文件，可能存在风险${NC}"
        else
            echo "${GREEN}✅ 系统目录扫描正常${NC}"
        fi
        
    else
        echo "${BLUE}无ROOT模式基础病毒扫描${NC}"
        
        # 应用分析
        echo "🔍 分析应用行为..."
        if [ -x "$(command -v pm)" ]; then
            TOTAL_APPS=$(pm list packages 2>/dev/null | wc -l)
            USER_APPS=$(pm list packages -3 2>/dev/null | wc -l)
            echo "  总应用数: $TOTAL_APPS"
            echo "  用户应用: $USER_APPS"
            
            if [ $USER_APPS -gt 50 ]; then
                echo "${YELLOW}⚠️  用户应用较多，建议检查未知来源应用${NC}"
            fi
        fi
        
        # 权限分析
        echo "🔍 检查危险权限..."
        if [ -x "$(command -v dumpsys)" ]; then
            DANGEROUS_PERMS=$(dumpsys package | grep -E "android.permission.READ_LOGS|android.permission.WRITE_SECURE_SETTINGS" | wc -l)
            echo "  危险权限应用: $DANGEROUS_PERMS 个"
        fi
    fi
    
    # 通用病毒特征检测
    echo "🔍 检测常见病毒特征..."
    VIRUS_INDICATORS=0
    
    # 检查异常进程名
    if [ -x "$(command -v ps)" ]; then
        SUSPICIOUS_PROCS=$(ps -ef 2>/dev/null | grep -i -E "miner|botnet|trojan|virus|malware" | wc -l)
        if [ $SUSPICIOUS_PROCS -gt 0 ]; then
            echo "${RED}⚠️  发现可疑进程名称${NC}"
            VIRUS_INDICATORS=$(expr "$VIRUS_INDICATORS" + 1)
        fi
    fi
    
    # 检查异常网络连接
    if [ -x "$(command -v netstat)" ]; then
        SUSPICIOUS_PORTS=$(netstat -an 2>/dev/null | grep -E ":4444|:5555|:6666|:7777|:8888" | wc -l)
        if [ $SUSPICIOUS_PORTS -gt 0 ]; then
            echo "${RED}⚠️  发现可疑端口连接${NC}"
            VIRUS_INDICATORS=$(expr "$VIRUS_INDICATORS" + 1)
        fi
    fi
    
    # 检查异常文件
    SUSPICIOUS_FILES=$(find /sdcard /data -name "*.apk" 2>/dev/null | grep -i -E "update|patch|fix|crack" | wc -l)
    if [ $SUSPICIOUS_FILES -gt 0 ]; then
        echo "${YELLOW}⚠️  发现可疑APK文件${NC}"
        VIRUS_INDICATORS=$(expr "$VIRUS_INDICATORS" + 1)
    fi
    
    if [ $VIRUS_INDICATORS -eq 0 ]; then
        echo "${GREEN}✅ 未发现明显病毒特征${NC}"
    else
        echo "${RED}❌ 发现 $VIRUS_INDICATORS 个潜在病毒特征${NC}"
    fi
}
block_security_risk() {
    local risk_type=$1
    local risk_detail=$2
    local retry_count=2
    echo -e "\n${CYAN}🔧 正在执行风险拦截操作（最多重试${retry_count}次）...${NC}"
    case $risk_type in
        "abnormal_ip")
            local risk_pids=$(netstat -anp 2>/dev/null | grep -E "ESTABLISHED" | grep -v -E "127.0.0.1|192.168.|10.|172.(1[6-9]|2[0-9]|3[0-1]).|100.64." | awk '{print $7}' | cut -d/ -f1 | sort -u | grep -v "^-$")
            if [ -n "$risk_pids" ]; then
                for pid in $risk_pids; do
                    if [ -n "$pid" ] && [ "$pid" -gt 0 ]; then
                        local success=0
                        local i=1
                        while [ "$i" -le "$retry_count" ]; do
                            echo "第$i次尝试：终止异常IP连接的进程（PID: $pid）"
                            kill -9 "$pid" 2>/dev/null
                            if ! ps -p "$pid" >/dev/null 2>&1; then
                                echo "  ✅ 进程 $pid 已终止，异常连接已拦截"
                                success=1
                                break
                            else
                                echo "  ⚠️  第$i次终止失败，重试中..."
                                sleep 1
                            fi
                            i=$(expr "$i" + 1)
                        done
                        if [ "$success" -eq 0 ]; then
                            echo "  ❌ 进程 $pid 终止失败（经${retry_count}次重试，需手动处理）"
                        fi
                    fi
                done
            else
                echo "  ➡️  无符合条件的异常IP连接进程，无需拦截"
            fi
            ;;
        "open_port")
            local risk_pids=$(netstat -anp 2>/dev/null | grep -E "LISTENING" | grep -v -E "127.0.0.1|5555" | awk '{print $7}' | cut -d/ -f1 | sort -u | grep -v "^-$")
            if [ -n "$risk_pids" ]; then
                for pid in $risk_pids; do
                    if [ -n "$pid" ] && [ "$pid" -gt 0 ]; then
                        local success=0
                        local i=1
                        while [ "$i" -le "$retry_count" ]; do
                            echo "第$i次尝试：终止监听开放端口的进程（PID: $pid）"
                            kill -9 "$pid" 2>/dev/null
                            if ! ps -p "$pid" >/dev/null 2>&1; then
                                echo "  ✅ 进程 $pid 已终止，开放端口已关闭"
                                success=1
                                break
                            else
                                echo "  ⚠️  第$i次终止失败，重试中..."
                                sleep 1
                            fi
                            i=$(expr "$i" + 1)
                        done
                        if [ "$success" -eq 0 ]; then
                            echo "  ❌ 进程 $pid 终止失败（经${retry_count}次重试，需手动处理）"
                        fi
                    fi
                done
            else
                echo "  ➡️  无符合条件的开放端口进程，无需拦截"
            fi
            ;;
        "virus_threat")
            echo "正在处理病毒威胁..."
            # 终止可疑进程
            if [ -x "$(command -v ps)" ]; then
                SUSPICIOUS_PIDS=$(ps -ef 2>/dev/null | grep -i -E "miner|botnet|trojan" | awk '{print $2}')
                for pid in $SUSPICIOUS_PIDS; do
                    kill -9 "$pid" 2>/dev/null && echo "  ✅ 终止可疑进程: $pid"
                done
            fi
            # 删除可疑APK
            find /sdcard /data -name "*.apk" 2>/dev/null | grep -i -E "update|patch|fix|crack" | while read apk; do
                rm -f "$apk" 2>/dev/null && echo "  ✅ 删除可疑文件: $(basename "$apk")"
            done
            ;;
        "root_proc")
            local risk_procs=$(echo "$risk_detail" | grep -v -E "com.android.|com.google.|com.huawei.|com.xiaomi.")
            if [ -n "$risk_procs" ]; then
                for proc_info in $risk_procs; do
                    local pid=$(echo "$proc_info" | grep -o "PID:[0-9]*" | cut -d: -f2 | grep -E "^[0-9]+$")
                    local proc_name=$(echo "$proc_info" | awk '{print $1}')
                    if [ -n "$pid" ] && [ "$pid" -gt 0 ]; then
                        local success=0
                        local i=1
                        while [ "$i" -le "$retry_count" ]; do
                            echo "第$i次尝试：终止非系统root进程（$proc_name PID: $pid）"
                            kill -9 "$pid" 2>/dev/null
                            if ! ps -p "$pid" >/dev/null 2>&1; then
                                echo "  ✅ 风险进程 $proc_name 已终止"
                                success=1
                                break
                            else
                                echo "  ⚠️  第$i次终止失败，重试中..."
                                sleep 1
                            fi
                            i=$(expr "$i" + 1)
                        done
                        if [ "$success" -eq 0 ]; then
                            echo "  ❌ 风险进程 $proc_name 终止失败（经${retry_count}次重试，需手动处理）"
                        fi
                    fi
                done
            else
                echo "  ➡️  无符合条件的非系统root进程，无需拦截"
            fi
            ;;
        "high_cpu_proc")
            local risk_procs=$(echo "$risk_detail" | awk '$5+0 > 30')
            if [ -n "$risk_procs" ]; then
                for proc_info in $risk_procs; do
                    local pid=$(echo "$proc_info" | grep -o "PID:[0-9]*" | cut -d: -f2 | grep -E "^[0-9]+$")
                    local proc_name=$(echo "$proc_info" | awk '{print $1}')
                    local cpu_usage=$(echo "$proc_info" | grep -o "占用率:[0-9]*%" | cut -d: -f2 | cut -d% -f1)
                    if [ -n "$pid" ] && [ "$pid" -gt 0 ]; then
                        echo -n "是否终止高CPU占用进程（$proc_name PID: $pid，占用率:${cpu_usage}%）？(是/否): "
                        read confirm
                        if [ "$confirm" = "是" ]; then
                            local success=0
                            local i=1
                            while [ "$i" -le "$retry_count" ]; do
                                echo "第$i次尝试：终止进程 $proc_name（PID: $pid）"
                                kill -9 "$pid" 2>/dev/null
                                if ! ps -p "$pid" >/dev/null 2>&1; then
                                    echo "  ✅ 进程 $proc_name 已终止，CPU占用恢复正常"
                                    success=1
                                    break
                                else
                                    echo "  ⚠️  第$i次终止失败，重试中..."
                                    sleep 1
                                fi
                                i=$(expr "$i" + 1)
                            done
                            if [ "$success" -eq 0 ]; then
                                echo "  ❌ 进程 $proc_name 终止失败（经${retry_count}次重试，需手动处理）"
                            fi
                        else
                            echo "  ➡️  已跳过进程 $proc_name 终止操作"
                        fi
                    fi
                done
            else
                echo "  ➡️  无符合条件的高CPU占用进程，无需拦截"
            fi
            ;;
        "data_perm")
            local current_perm=$(ls -ld /data | awk '{print $1}')
            if [ "$current_perm" != "drwxrwx--x" ]; then
                echo "正在修复/data目录权限（目标：drwxrwx--x）"
                chmod 771 /data 2>/dev/null
                local new_perm=$(ls -ld /data | awk '{print $1}')
                if [ "$new_perm" = "drwxrwx--x" ]; then
                    echo "  ✅ /data目录权限已修复为771，核心数据安全"
                else
                    echo "  ❌ /data目录权限修复失败（需root权限，当前权限：${new_perm}）"
                fi
            else
                echo "  ➡️  /data目录权限已正常，无需修复"
            fi
            ;;
        "hosts_perm")
            local current_perm=$(ls -l /system/etc/hosts 2>/dev/null | awk '{print $1}')
            if [ -n "$current_perm" ] && [ "$current_perm" != "-rw-r--r--" ]; then
                echo "正在修复/system/etc/hosts文件权限（目标：-rw-r--r--）"
                chmod 644 /system/etc/hosts 2>/dev/null
                local new_perm=$(ls -l /system/etc/hosts 2>/dev/null | awk '{print $1}')
                if [ "$new_perm" = "-rw-r--r--" ]; then
                    echo "  ✅ hosts文件权限已修复为644，防止网址劫持"
                else
                    echo "  ❌ hosts文件权限修复失败（需root权限，当前权限：${new_perm}）"
                fi
            else
                echo "  ➡️  hosts文件权限已正常，无需修复"
            fi
            ;;
        "usb_debug")
            echo "正在关闭USB调试功能（覆盖多系统属性）"
            setprop persist.sys.usb.config "mtp" 2>/dev/null
            setprop sys.usb.config "mtp" 2>/dev/null
            local usb_state=$(getprop persist.sys.usb.config 2>/dev/null | grep "adb")
            if [ -z "$usb_state" ]; then
                echo "  ✅ USB调试已关闭，外接设备无法通过adb访问数据"
            else
                echo "  ❌ USB调试关闭失败（当前状态：$(getprop persist.sys.usb.config)，需手动在设置中关闭）"
            fi
            ;;
        "unknown_source")
            echo "正在关闭未知来源应用安装功能"
            setprop ro.settings.security.enable_unknown_source "0" 2>/dev/null
            setprop persist.sys.unknown_source "0" 2>/dev/null
            local unknown_state=$(getprop ro.settings.security.enable_unknown_source 2>/dev/null)
            if [ "$unknown_state" = "0" ] || [ -z "$unknown_state" ]; then
                echo "  ✅ 未知来源安装已关闭，仅允许应用商店安装应用"
            else
                echo "  ❌ 未知来源安装关闭失败（当前状态：${unknown_state}，需手动在设置中关闭）"
            fi
            ;;
        "suspicious_apk")
            local apk_list=$(find /sdcard -name "*.apk" -type f 2>/dev/null | grep -v -E "backup|update" | sort -r | tail -n +4)
            if [ -n "$apk_list" ]; then
                echo "正在删除/sdcard目录下多余可疑APK（保留前3个，排除备份/更新包）"
                local delete_count=0
                echo "$apk_list" | while read apk_path; do
                    if [ -f "$apk_path" ]; then
                        rm -f "$apk_path" 2>/dev/null
                        if [ $? -eq 0 ]; then
                            echo "  ✅ 已删除可疑APK：$(basename "$apk_path")"
                            delete_count=$(expr "$delete_count" + 1)
                        else
                            echo "  ❌ 无法删除APK：$(basename "$apk_path")（权限不足）"
                        fi
                    fi
                done
                echo "  ➡️  共删除 ${delete_count} 个可疑APK"
            else
                echo "  ➡️  /sdcard目录APK数量≤3或均为备份包，无需删除"
            fi
            ;;
    esac
    echo -e "\n${GREEN}当前风险类型拦截操作执行完成！${NC}"
}
check_and_block_security_risk() {
    echo "${CYAN}Hacker${NC}"
    show_separator
    
    # 选择检测模式
    echo "请选择安全检测模式:"
    echo "1. ROOT模式深度检测 (需要root权限)"
    echo "2. 无ROOT模式基础检测"
    echo "0. 返回主菜单"
    echo
    echo -n "请选择: "
    read mode_choice
    case $mode_choice in
        1)
            if [ $(id -u) -ne 0 ]; then
                echo "${RED}未获取ROOT权限，切换到无ROOT模式${NC}"
                DETECTION_MODE="normal"
            else
                DETECTION_MODE="root"
                echo "${RED}ROOT模式深度安全检测${NC}"
            fi
            ;;
        2)
            DETECTION_MODE="normal"
            echo "${BLUE}无ROOT模式基础安全检测${NC}"
            ;;
        0)
            return
            ;;
        *)
            echo "${RED}无效选择，使用无ROOT模式${NC}"
            DETECTION_MODE="normal"
            ;;
    esac
    show_separator
    RISK_COUNT=0
    RISK_LIST=()
    
    echo "${WHITE}【1. 网络安全检测】${NC}"
    if [ -x "$(command -v netstat)" ]; then
        ABNORMAL_IP_LIST=$(netstat -an 2>/dev/null | grep -E "ESTABLISHED" | grep -v -E "127.0.0.1|192.168.|10.|172.(1[6-9]|2[0-9]|3[0-1]).|100.64." | awk '{print $5}' | cut -d: -f1 | sort -u | grep -v "^$")
        ABNORMAL_IP_NUM=$(echo "$ABNORMAL_IP_LIST" | wc -l)
        if [ "$ABNORMAL_IP_NUM" -gt 0 ] && [ -n "$ABNORMAL_IP_LIST" ]; then
            echo "${RED}⚠️  风险位置：网络连接${NC}"
            echo "   风险详情：发现 ${ABNORMAL_IP_NUM} 个非局域网/非运营商IP连接，可能泄露数据"
            RISK_COUNT=$(expr "$RISK_COUNT" + 1)
            RISK_LIST+=("abnormal_ip|$ABNORMAL_IP_LIST")
        else
            echo "${GREEN}✅ 未发现异常网络连接${NC}"
        fi
        OPEN_PORTS=$(netstat -an 2>/dev/null | grep -E "LISTENING" | grep -v -E "127.0.0.1|5555" | awk '{print $4}' | cut -d: -f2 | sort -u | grep -v "^$")
        OPEN_PORT_NUM=$(echo "$OPEN_PORTS" | wc -l)
        if [ "$OPEN_PORT_NUM" -gt 0 ] && [ -n "$OPEN_PORTS" ]; then
            echo "${RED}⚠️  风险位置：系统端口${NC}"
            echo "   风险详情：发现 ${OPEN_PORT_NUM} 个非系统必要对外开放端口，可能被恶意利用"
            RISK_COUNT=$(expr "$RISK_COUNT" + 1)
            RISK_LIST+=("open_port|$OPEN_PORTS")
        else
            echo "${GREEN}✅ 未发现异常对外开放端口${NC}"
        fi
    else
        echo "❓ 缺少netstat工具，无法检测网络连接"
    fi
    echo -e "\n${WHITE}【2. 异常进程检测】${NC}"
    if [ -x "$(command -v ps)" ]; then
        ROOT_PROC_LIST=$(ps -ef 2>/dev/null | grep -v "grep" | grep -v -E "/system/|/vendor/|/sbin/|com.android.|com.google.|com.huawei.|com.xiaomi." | grep "root" | awk '{print $8 " (PID:" $2 ")"}' | grep -v "^$")
        ROOT_PROC_NUM=$(echo "$ROOT_PROC_LIST" | wc -l)
        if [ "$ROOT_PROC_NUM" -gt 0 ] && [ -n "$ROOT_PROC_LIST" ]; then
            echo "${RED}⚠️  风险位置：后台进程${NC}"
            echo "   风险详情：发现 ${ROOT_PROC_NUM} 个非系统/非厂商root进程，可能是恶意程序"
            RISK_COUNT=$(expr "$RISK_COUNT" + 1)
            RISK_LIST+=("root_proc|$ROOT_PROC_LIST")
        else
            echo "${GREEN}✅ 未发现异常root进程${NC}"
        fi
    else
        echo "❓ 缺少ps工具，无法检测进程"
    fi
    if [ -x "$(command -v top)" ]; then
        HIGH_CPU_PROC=$(top -b -n 1 2>/dev/null | grep -v "grep" | grep -v -E "system_server|surfaceflinger|zygote" | awk '$9 > 30 {print $12 " (PID:" $1 ") 占用率:" $9 "%"}' | grep -v "^$")
        HIGH_CPU_NUM=$(echo "$HIGH_CPU_PROC" | wc -l)
        if [ "$HIGH_CPU_NUM" -gt 0 ] && [ -n "$HIGH_CPU_PROC" ]; then
            echo "${YELLOW}⚠️  风险位置：资源占用${NC}"
            echo "   风险详情：发现 ${HIGH_CPU_NUM} 个高CPU占用进程，可能偷跑资源"
            RISK_COUNT=$(expr "$RISK_COUNT" + 1)
            RISK_LIST+=("high_cpu_proc|$HIGH_CPU_PROC")
        else
            echo "${GREEN}✅ 未发现异常高CPU占用进程${NC}"
        fi
    else
        echo "❓ 缺少top工具，无法检测CPU占用"
    fi
    echo -e "\n${WHITE}【3. 系统权限检测】${NC}"
    if [ -d "/data" ]; then
        DATA_PERM=$(ls -ld /data | awk '{print $1}')
        if [ "$DATA_PERM" != "drwxrwx--x" ] && [ "$DATA_PERM" != "drwxrwxr-x" ]; then
            echo "${RED}⚠️  风险位置：目录权限${NC}"
            echo "   风险详情：/data目录权限异常（当前：${DATA_PERM}），可能泄露数据"
            RISK_COUNT=$(expr "$RISK_COUNT" + 1)
            RISK_LIST+=("data_perm|$DATA_PERM")
        else
            echo "${GREEN}✅ /data目录权限正常${NC}"
        fi
    else
        echo "❓ 无法访问/data目录，权限检测失败"
    fi
    if [ -f "/system/etc/hosts" ]; then
        HOSTS_PERM=$(ls -l /system/etc/hosts | awk '{print $1}')
        if [ "$HOSTS_PERM" != "-rw-r--r--" ] && [ "$HOSTS_PERM" != "-r--r--r--" ]; then
            echo "${RED}⚠️  风险位置：文件权限${NC}"
            echo "   风险详情：hosts文件权限异常（当前：${HOSTS_PERM}），可能被劫持"
            RISK_COUNT=$(expr "$RISK_COUNT" + 1)
            RISK_LIST+=("hosts_perm|$HOSTS_PERM")
        else
            echo "${GREEN}✅ hosts文件权限正常${NC}"
        fi
    else
        echo "❓ /system/etc/hosts文件不存在，权限检测失败"
    fi
    echo -e "\n${WHITE}【4. 系统安全设置检测】${NC}"
    USB_DEBUG1=$(getprop persist.sys.usb.config 2>/dev/null | grep "adb" | wc -l)
    USB_DEBUG2=$(getprop sys.usb.config 2>/dev/null | grep "adb" | wc -l)
    if [ "$USB_DEBUG1" -eq 1 ] || [ "$USB_DEBUG2" -eq 1 ]; then
        echo "${RED}⚠️  风险位置：系统设置${NC}"
        echo "   风险详情：USB调试已开启，陌生设备可能读取手机数据"
        RISK_COUNT=$(expr "$RISK_COUNT" + 1)
        RISK_LIST+=("usb_debug|开启")
    else
        echo "${GREEN}✅ USB调试已关闭${NC}"
    fi
    ANDROID_SDK=$(getprop ro.build.version.sdk 2>/dev/null)
    if [ $(expr "$ANDROID_SDK" \>= 26) -eq 1 ]; then
        UNKNOWN_SOURCE=$(getprop ro.settings.security.enable_unknown_source 2>/dev/null)
        if [ "$UNKNOWN_SOURCE" = "1" ]; then
            echo "${RED}⚠️  风险位置：系统设置${NC}"
            echo "   风险详情：未知来源安装已开启（Android 8+），可能误装恶意APK"
            RISK_COUNT=$(expr "$RISK_COUNT" + 1)
            RISK_LIST+=("unknown_source|开启")
        else
            echo "${GREEN}✅ 未知来源安装已关闭（Android 8+）${NC}"
        fi
    else
        UNKNOWN_SOURCE=$(getprop persist.sys.unknown_source 2>/dev/null)
        if [ "$UNKNOWN_SOURCE" = "1" ]; then
            echo "${RED}⚠️  风险位置：系统设置${NC}"
            echo "   风险详情：未知来源安装已开启（Android 7及以下），可能误装恶意APK"
            RISK_COUNT=$(expr "$RISK_COUNT" + 1)
            RISK_LIST+=("unknown_source|开启")
        else
            echo "${GREEN}✅ 未知来源安装已关闭（Android 7及以下）${NC}"
        fi
    fi
    echo -e "\n${WHITE}【5. 可疑文件检测】${NC}"
    if [ -d "/sdcard" ]; then
        SUSPICIOUS_APK=$(find /sdcard -name "*.apk" -type f 2>/dev/null | grep -v -E "backup|update" | wc -l)
        if [ "$SUSPICIOUS_APK" -gt 3 ]; then
            echo "${YELLOW}⚠️  风险位置：存储文件${NC}"
            echo "   风险详情：/sdcard目录有 ${SUSPICIOUS_APK} 个非备份/非更新APK（建议≤3个），可能含恶意代码"
            RISK_COUNT=$(expr "$RISK_COUNT" + 1)
            RISK_LIST+=("suspicious_apk|${SUSPICIOUS_APK}个")
        else
            echo "${GREEN}✅ /sdcard目录APK数量正常${NC}"
        fi
    else
        echo "❓ 无法访问/sdcard目录，文件检测失败"
    fi
    # 新增：病毒与恶意软件检测
    check_virus_threats "$DETECTION_MODE"
    VIRUS_INDICATORS=$?
    if [ $VIRUS_INDICATORS -gt 0 ]; then
        RISK_COUNT=$(expr "$RISK_COUNT" + 1)
        RISK_LIST+=("virus_threat|${VIRUS_INDICATORS}个特征")
    fi
    echo -e "\n${WHITE}【6. 风险处理】${NC}"
    if [ "$RISK_COUNT" -gt 0 ]; then
        echo "${RED}❌ 共发现 ${RISK_COUNT} 处安全隐患，是否执行拦截/关闭操作？(是/否): ${NC}"
        read confirm_block
        if [ "$confirm_block" = "是" ]; then
            local risk_index=0
            for risk in "${RISK_LIST[@]}"; do
                risk_type=$(echo "$risk" | cut -d| -f1)
                risk_detail=$(echo "$risk" | cut -d| -f2)
                block_security_risk "$risk_type" "$risk_detail"
                show_separator
                risk_index=$(expr "$risk_index" + 1)
            done
        else
            echo "${YELLOW}➡️  已跳过风险拦截操作，请后续手动处理隐患${NC}"
        fi
    else
        echo "${GREEN}✅ 未发现任何安全隐患，手机基础安全状态良好${NC}"
    fi
    show_separator
    echo
}
manage_apps() {
    echo "${GREEN}Hacker（此功能维护，等待修复）${NC}"
    show_separator
    
    if [ ! -x "$(command -v pm)" ]; then
        echo "${RED}错误：系统缺少pm工具，无法管理应用${NC}"
        show_separator
        echo
        return
    fi
    echo "正在获取非系统应用列表（含存储占用和包名）...\n"
    if pm list packages -3 >/dev/null 2>&1; then
        USER_APPS=$(pm list packages -3 2>/dev/null | awk -F: '{print $2}' | while read pkg; do
            pm list packages -f "$pkg" 2>/dev/null | awk -F: '{print $2}' | awk '{print $1 " " $2}'
        done)
    else
        USER_APPS=$(pm list packages -f 2>/dev/null | grep -v -E "/system/app/|/system/priv-app/|/vendor/app/|/odm/app/|/oem/app/" | awk -F: '{print $2}' | awk '{print $1 " " $2}')
    fi
    
    USER_APPS=$(echo "$USER_APPS" | grep -v "^$" | sort -u)
    if [ -z "$USER_APPS" ]; then
        echo "${YELLOW}未检测到非系统应用（仅显示用户安装的第三方应用）${NC}"
        show_separator
        echo
        return
    fi
    APP_LIST=()
    echo "${WHITE}非系统应用列表：${NC}"
    printf "%-5s | %-22s | %-30s | %-8s\n" "序号" "应用名" "包名" "存储占用"
    echo "-----|------------------------|------------------------------|----------"
    index=1
    while read -r app_info; do
        pkg_name=$(echo "$app_info" | awk '{print $1}')
        app_path=$(echo "$app_info" | awk '{$1="";print $0}' | sed 's/^ //')
        
        app_name=$(pm dump "$pkg_name" 2>/dev/null | grep -A1 "ApplicationInfo" | grep "label=" | cut -d= -f2 | sed 's/^"//;s/"$//' | grep -v "^$")
        if [ -z "$app_name" ]; then
            app_name=$(basename "$app_path" .apk)
        fi
        app_name=$(echo "$app_name" | awk '{if(length($0)>22) print substr($0,1,19)"..."; else print $0}')
        app_name=$(printf "%-22s" "$app_name")
        
        app_size_apk=$(du -sh "$app_path" 2>/dev/null | awk '{print $1}')
        app_size_data=$(du -sh "/data/data/$pkg_name" 2>/dev/null | awk '{print $1}')
        if [ -n "$app_size_data" ] && [ "$app_size_data" != "0" ]; then
            app_size="${app_size_apk}(APK)+${app_size_data}(数据)"
        else
            app_size="${app_size_apk:-未知}"
        fi
        
        pkg_name=$(printf "%-30s" "$pkg_name")
        
        printf "%-5d | %s | %s | %-8s\n" "$index" "$app_name" "$pkg_name" "$app_size"
        
        APP_LIST+=("$index:$pkg_name:$app_name:$app_size")
        index=$(expr "$index" + 1)
    done <<< "$USER_APPS"
    echo -e "\n${WHITE}请输入要卸载的应用序号（多个序号用空格分隔，输入0取消）：${NC}"
    echo -n "输入序号: "
    read -r app_indices
    if [ "$app_indices" = "0" ] || [ -z "$app_indices" ]; then
        echo "${GREEN}已取消卸载操作${NC}"
        show_separator
        echo
        return
    fi
    for app_index in $app_indices; do
        if ! echo "$app_index" | grep -qE "^[0-9]+$"; then
            echo "${RED}无效序号：${app_index}（需为数字），跳过${NC}"
            continue
        fi
        valid=0
        target_pkg=""
        target_app_name=""
        for app in "${APP_LIST[@]}"; do
            idx=$(echo "$app" | cut -d: -f1)
            if [ "$idx" -eq "$app_index" ]; then
                target_pkg=$(echo "$app" | cut -d: -f2 | sed 's/ *$//')
                target_app_name=$(echo "$app" | cut -d: -f3 | sed 's/ *$//')
                valid=1
                break
            fi
        done
        if [ "$valid" -eq 0 ]; then
            echo "${RED}无效序号：${app_index}，跳过${NC}"
            continue
        fi
        echo -e "\n${YELLOW}确认卸载应用：${target_app_name}（包名：${target_pkg}）？(是/否，默认否): ${NC}"
        read -r confirm_uninstall
        confirm_uninstall=${confirm_uninstall:-"否"}
        if [ "$confirm_uninstall" != "是" ]; then
            echo "${GREEN}已取消卸载 ${target_app_name}${NC}"
            continue
        fi
        echo "正在终止 ${target_app_name} 的相关进程..."
        app_pids=$(ps -ef 2>/dev/null | grep "$target_pkg" | grep -v "grep" | awk '{print $2}')
        if [ -n "$app_pids" ]; then
            for pid in $app_pids; do
                kill -9 "$pid" 2>/dev/null
            done
            echo "  ✅ ${target_app_name} 相关进程已终止"
        fi
        echo "正在卸载 ${target_app_name}..."
        uninstall_result=$(pm uninstall "$target_pkg" 2>&1)
        if [ $? -eq 0 ] || echo "$uninstall_result" | grep -q "Success"; then
            echo "${GREEN}✅ 卸载成功：${target_app_name}${NC}"
        else
            echo "${RED}❌ 常规卸载失败：${uninstall_result}${NC}"
            echo -n "是否尝试保留应用数据卸载？(是/否): "
            read -r keep_data
            if [ "$keep_data" = "是" ]; then
                uninstall_keep_result=$(pm uninstall -k "$target_pkg" 2>&1)
                if [ $? -eq 0 ] || echo "$uninstall_keep_result" | grep -q "Success"; then
                    echo "${GREEN}✅ 保留数据卸载成功：${target_app_name}${NC}"
                else
                    echo "${RED}❌ 保留数据卸载也失败：${uninstall_keep_result}${NC}"
                fi
            fi
        fi
    done
    show_separator
    echo
}
weather_query() {
    echo "${CYAN}Hacker${NC}"
    show_separator
    
    if [ ! -x "$(command -v curl)" ] && [ ! -x "$(command -v wget)" ]; then
        echo "${RED}错误：系统缺少curl或wget，无法调用天气接口${NC}"
        show_separator
        echo
        return
    fi
    echo "天气查询功能"
    echo -n "请输入省份 (如: 四川): "
    read province
    echo -n "请输入城市 (如: 绵阳): "
    read city
    if [ -z "$province" ] || [ -z "$city" ]; then
        echo "${RED}错误：省份和城市不能为空${NC}"
        show_separator
        echo
        return
    fi
    echo -e "\n正在获取 ${province}${city} 的天气信息...\n"
    # URL编码函数
    urlencode() {
        echo "$1" | sed 's/ /%20/g'
    }
    PROVINCE_ENCODED=$(urlencode "$province")
    CITY_ENCODED=$(urlencode "$city")
    
    WEATHER_URL="https://cn.apihz.cn/api/tianqi/tqyb.php?id=88888888&key=88888888&sheng=$PROVINCE_ENCODED&place=$CITY_ENCODED"
    if [ -x "$(command -v curl)" ]; then
        WEATHER_DATA=$(curl -s --connect-timeout 10 "$WEATHER_URL" 2>/dev/null)
    else
        WEATHER_DATA=$(wget -q -T 10 -O - "$WEATHER_URL" 2>/dev/null)
    fi
    if [ -z "$WEATHER_DATA" ] || echo "$WEATHER_DATA" | grep -q "error"; then
        echo "${RED}获取天气信息失败！${NC}"
        echo "可能原因:"
        echo "1. 网络连接问题"
        echo "2. 接口暂时不可用"
        echo "3. 省份城市名称不正确"
        echo -e "\n${YELLOW}请检查省份城市名称后重试${NC}"
    else
        echo "${WHITE}${province}${city} 天气信息：${NC}"
        echo "$WEATHER_DATA" | while read line; do
            echo "  $line"
        done
    fi
    show_separator
    echo
}

# -------------------------- 优化部分：直链下载（添加实时进度条） --------------------------
direct_link_download() {
    echo "${PURPLE}Hacker${NC}"
    show_separator
    
    # 检查下载工具（curl/wget）是否存在
    if [ ! -x "$(command -v curl)" ] && [ ! -x "$(command -v wget)" ]; then
        echo "${RED}错误：系统缺少curl或wget，无法执行下载${NC}"
        show_separator
        echo
        return
    fi
    # 检查目标存储目录是否存在且可写
    DOWNLOAD_DIR="/storage/emulated/0/"
    if [ ! -d "$DOWNLOAD_DIR" ] || [ ! -w "$DOWNLOAD_DIR" ]; then
        echo "${RED}错误：下载目录 ${DOWNLOAD_DIR} 不存在或无写入权限${NC}"
        show_separator
        echo
        return
    fi
    # 提示用户输入外链并验证格式
    echo "直链下载功能（文件将保存至：${DOWNLOAD_DIR}）"
    echo -n "请输入资源外链（如https://xxx.com/file.zip）："
    read DOWNLOAD_URL
    if [ -z "$DOWNLOAD_URL" ] || ! echo "$DOWNLOAD_URL" | grep -qE "^https?://"; then
        echo "${RED}错误：无效的外链，请输入以http或https开头的链接${NC}"
        show_separator
        echo
        return
    fi
    # 提取或生成文件名
    FILENAME=$(basename "$DOWNLOAD_URL" | sed 's/\?.*//')  # 去除URL参数，保留原始文件名
    if [ -z "$FILENAME" ]; then
        FILENAME="download_$(date +%Y%m%d%H%M%S).tmp"  # 无文件名时用时间戳命名
    fi
    SAVE_PATH="${DOWNLOAD_DIR}${FILENAME}"
    # 确认下载信息并执行下载
    echo -e "\n${YELLOW}即将下载：${NC}"
    echo "资源链接：$DOWNLOAD_URL"
    echo "保存路径：$SAVE_PATH"
    echo -n "是否开始下载？(是/否): "
    read CONFIRM
    if [ "$CONFIRM" != "是" ]; then
        echo "${GREEN}已取消下载操作${NC}"
        show_separator
        echo
        return
    fi
    # 优先用curl下载（带进度条），无curl则用wget（带进度条）
    echo -e "\n开始下载...（请勿中断脚本）\n"
    if [ -x "$(command -v curl)" ]; then
        # curl -# 显示进度条，-L 自动重定向，-o 指定输出文件
        curl -# -L -o "$SAVE_PATH" "$DOWNLOAD_URL" 2>/dev/null
    else
        # wget --progress=bar:force 显示进度条，-O 指定输出文件
        wget --progress=bar:force -O "$SAVE_PATH" "$DOWNLOAD_URL" 2>/dev/null
    fi
    # 检查下载结果并反馈
    if [ $? -eq 0 ] && [ -f "$SAVE_PATH" ]; then
        FILE_SIZE=$(du -sh "$SAVE_PATH" | awk '{print $1}')
        echo -e "\n${GREEN}✅ 下载完成！${NC}"
        echo "文件名称：$FILENAME"
        echo "文件大小：$FILE_SIZE"
        echo "保存位置：$SAVE_PATH"
    else
        # 下载失败时删除残留文件
        [ -f "$SAVE_PATH" ] && rm -f "$SAVE_PATH"
        echo -e "\n${RED}❌ 下载失败！${NC}"
        echo "可能原因：链接无效、网络中断、资源不存在或无访问权限"
    fi
    show_separator
    echo
}

# -------------------------- 新增部分：ROOT专区（重置安卓设备ID） --------------------------
root_special_zone() {
    echo "${RED}Hacker - ROOT专区${NC}"
    show_separator
    
    # 检查是否拥有ROOT权限
    if [ $(id -u) -ne 0 ]; then
        echo "${RED}❌ 未获取ROOT权限，无法使用ROOT专区功能${NC}"
        echo "提示：需先给脚本授予ROOT权限（如通过Magisk、SuperSU）"
        show_separator
        echo
        return
    fi
    # ROOT专区菜单
    echo "ROOT专区功能（需ROOT权限）:"
    echo "1. 重置安卓设备ID（恢复出厂级设备标识）"
    echo "0. 返回主菜单"
    echo
    echo -n "请选择功能: "
    read root_choice
    case $root_choice in
        1)
            echo -e "\n${YELLOW}⚠️  警告：重置设备ID会导致以下影响${NC}"
            echo "1. 部分应用（如社交、支付类）需重新登录"
            echo "2. 基于设备ID的服务（如推送、授权）可能异常"
            echo "3. 操作不可逆，需重启手机生效"
            echo -n "\n是否确认重置设备ID？(输入'确认重置'执行，其他取消): "
            read confirm_reset
            if [ "$confirm_reset" != "确认重置" ]; then
                echo "${GREEN}\n已取消设备ID重置操作${NC}"
                show_separator
                echo
                return
            fi
            # 核心：重置关键设备ID文件（覆盖主流安卓设备路径）
            echo -e "\n正在重置设备ID...\n"
            # 1. 重置Android ID（存储于settings.db）
            if [ -x "$(command -v sqlite3)" ] && [ -f "/data/data/com.android.providers.settings/databases/settings.db" ]; then
                echo "1. 重置Android ID..."
                sqlite3 /data/data/com.android.providers.settings/databases/settings.db "UPDATE secure SET value=hex(randomblob(8)) WHERE name='android_id';" 2>/dev/null
                if [ $? -eq 0 ]; then
                    echo "   ✅ Android ID重置成功"
                else
                    echo "   ❌ Android ID重置失败（可能需重启后重试）"
                fi
            else
                echo "   ❌ 缺少sqlite3工具或settings.db文件，无法重置Android ID"
            fi
            # 2. 删除设备标识缓存文件（部分设备存储路径）
            echo "2. 清理设备标识缓存..."
            ID_CACHE_PATHS=(
                "/data/system/users/0/settings_secure.xml"
                "/data/system/android_id"
                "/data/misc/android_id"
            )
            for cache_path in "${ID_CACHE_PATHS[@]}"; do
                if [ -f "$cache_path" ]; then
                    rm -f "$cache_path" 2>/dev/null && echo "   ✅ 删除缓存：$cache_path"
                fi
            done
            # 3. 提示重启生效
            echo -e "\n${GREEN}✅ 设备ID重置操作已执行！${NC}"
            echo "⚠️  重要：需立即重启手机，重置才能完全生效"
            echo "重启后建议：检查关键应用登录状态，重新授权必要服务"
            ;;
        0)
            return
            ;;
        *)
            echo "${RED}\n无效选择，请输入 0 或 1${NC}"
            ;;
    esac
    show_separator
    echo
}

# -------------------------- 菜单与主函数（仅添加ROOT专区选项） --------------------------
show_menu() {
    echo "请选择功能:"
    echo "1. 手机综合信息"
    echo "2. 执行储存清理"
    echo "3. 获取每日一言"
    echo "4. 安全隐患检测 (含病毒检测)"
    echo "5. 三方应用管理"
    echo "6. 天气查询"
    echo "7. 直链下载"
    echo "8. ROOT专区（需ROOT权限）"  # 新增ROOT专区选项
    echo "0. 退出此脚本"
    echo
    echo -n "Hacker: "
}

main() {
    if [ ! -x "$(command -v getprop)" ] && [ ! -f /system/build.prop ]; then
        echo "${RED}警告: 非标准Android环境，部分功能可能异常${NC}"
        echo
    fi
    
    while true; do
        show_title
        show_menu
        read choice
        
        case $choice in
            1)
                show_title
                get_all_phone_info
                ;;
            2)
                show_title
                clean_storage
                ;;
            3)
                show_title
                get_daily_quote
                ;;
            4)
                show_title
                check_and_block_security_risk
                ;;
            5)
                show_title
                manage_apps
                ;;
            6)
                show_title
                weather_query
                ;;
            7)
                show_title
                direct_link_download
                ;;
            8)  # 新增：调用ROOT专区功能
                show_title
                root_special_zone
                ;;
            0)
                echo "${GREEN}感谢使用，再见！${NC}"
                exit 0
                ;;
            *)
                echo "${RED}无效选择，请输入 0-8 的数字${NC}"
                ;;
        esac
        
        echo
        echo -n "按回车键返回菜单..."
        read
    done
}
main
