#!/system/bin/sh
# 多功能脚本v2.7.4 安卓原生Shell完整版
# 适配：/system/bin/sh(POSIX)，无Bash数组，含完整卡密验证+云更新+心跳
main(){
    #by.小宝
    # 检查是否为root用户
    if [ `id -u` -ne 0 ]; then
        echo -e "\033[31m用Root权限执行\033[0m"
        exit 1
    fi
     
    #设置当前时间定义
    now_time=$(date '+%Y-%m-%d %H:%M:%S')
         
    #颜色定义
    red_start="\033[31m"
    red_last="\033[0m"
    green="\033[32m"
    yellow="\033[33m"
    blue="\033[36m"
    bg_purple="\033[45m"
    bg_yellow="\033[43m"
         
#设置清理ano函数*****************************  
    kill_ano(){
        echo -e "适用于王者，和平，CF，使命召唤等游戏"
        sleep 1
        # 清理iptables规则 兼容无iptables设备
        if command -v iptables >/dev/null 2>&1; then
            iptables -F 2>/dev/null
            iptables -X 2>/dev/null
            iptables -Z 2>/dev/null
            iptables -t nat -F 2>/dev/null
            echo -e "本地缓存数据处理成功"
            echo -e "iptables规则清除成功"
            ip6tables=/system/bin/ip6tables
            iptables=/system/bin/iptables
        else
            echo -e "未检测到iptables，跳过规则清理"
        fi

        # POSIX兼容循环 替代Bash数组
        for game in \
            "com.tencent.tmgp.pubgmhd" \
            "com.tencent.ig" \
            "com.tencent.tmgp.cod" \
            "com.tencent.tmgp.sgame" \
            "com.tencent.tmgp.cf" \
            "com.tencent.tmgp.gnyx"
        do
            rm -rf /data/data/$game/files/ano_tmp 2>/dev/null
            rm -rf /data/user/0/$game/files/ano_tmp 2>/dev/null
        done

        #修复第三方环境异常
        echo 16384 > /proc/sys/fs/inotify/max_queued_events 2>/dev/null
        echo 128 > /proc/sys/fs/inotify/max_user_instances 2>/dev/null
        echo 8192 > /proc/sys/fs/inotify/max_user_watches 2>/dev/null
        
        #生成随机序列号
        echo -e "缓存数据清理完成"
        name=$(tr -dc '1-9' < /dev/urandom | head -c 8 2>/dev/null)
        while echo "$name" | grep -q "'" 2>/dev/null; do
            name=$(tr -dc '1-9' < /dev/urandom | head -c 8 2>/dev/null)
        done 
        resetprop ro.serialno $name 2>/dev/null
        echo -e "${green}Success_JG|随机序列号:$name${red_last}"
        echo -e "${red_start}清除成功！${red_last}"
        sleep 1    
    }

#定义终止进程函数*************************************
    kill_app(){
        echo -e "${bg_yellow}为了游戏方便所制作的此脚本"
        echo -e "终止除游戏外的所有进程，保证CPU无其他负担导致手机发烫严重"
        echo -e "为了确保进程完全终止，请重复执行3~5次！！${red_last}"
        sleep 2

        # 终止进程函数封装 避免冗余
        kill_process() {
            local name=$1
            local desc=$2
            echo -e "开始终止$desc程序，请等待"
            sleep 0.1
            local pid=$(ps -ef | grep "$name" | grep -v grep | awk '{print $2}' 2>/dev/null)
            if [ -z "$pid"  ]; then
                echo -e "${red_start}未检测到$desc程序，开始终止下一个...${red_last}"
            else
                for p in $pid; do
                    if kill -9 $p 2>/dev/null; then
                        echo -e "${red_start}终止成功！进程ID为$p${red_last}"
                    else
                        echo -e "${red_start}终止$desc进程失败！进程ID为$p${red_last}"
                    fi
                done
            fi
            echo -e "_____________________________________________________"
            sleep 0.1
        }

        # 调用终止进程
        kill_process "com.tencent.mm" "微信"
        kill_process "com.smile.gifmaker" "快手"
        kill_process "org.telegram.messenger" "TG"
        kill_process "com.tencent.mobileqq" "QQ"

        sleep 1
        clear
        echo -e "脚本启动时间为$now_time"     
    }

#自定义备份文件函数************************
    backup(){
        clear
        echo -e "请输入你要备份的文件目录："
        read -r package_name
        # 输入容错
        if [ -z "$package_name" ] || [ ! -e "$package_name" ]; then
            echo -e "${red_start}错误：目录不存在或输入为空，请重新执行！${red_last}"
            sleep 2
            return
        fi
        #定义需备份文件目录
        local needbackup_dir="$package_name"
        local backup_dir="/storage/emulated/0/Download/" 
        local date=$(date +%Y年%m月%d日%H时%M分%S秒) 
        local backup_file="backup_$date.tar.gz"
        
        # 创建备份目录
        mkdir -p "$backup_dir" 2>/dev/null
        # 执行备份
        tar -czf "${backup_dir}/${backup_file}" "$needbackup_dir" 2>/dev/null
        if [ $? -eq 0 ]; then
            echo -e "${green}备份成功！文件为:${backup_dir}${backup_file}${red_last}"
            clear
        else
            clear
            echo -e "${red_start}备份失败：请检查目录权限或磁盘空间！${red_last}"
            sleep 1
        fi
    }

#定义重启系统函数*****************************************
    reboot_system(){
        echo -e "${red_start}警告：即将重启设备！3秒后执行（按Ctrl+C取消）${red_last}"
        sleep 3
        reboot 2>/dev/null
        exit 0
    }

#PUBG过300秒函数*************************************
    kill_game(){
        clear
        echo -e "选择你需要去300秒的服:\n全球:com.pubg.krmobile\n日韩:com.pubg.krmobile\n台湾:com.rekoo.pubgm\n越南:com.vng.pubgmobile\n国体:com.tencent.igce"
        read -r package_name
        # POSIX兼容case 替代数组包含判断
        case "$package_name" in
            "com.tencent.ig"|"com.pubg.krmobile"|"com.rekoo.pubgm"|"com.vng.pubgmobile"|"com.tencent.igce")
                sleep 0.5
                killall $package_name 2>/dev/null
                echo -e "${green}SUCCESS${red_last}"
                # 清理登录文件
                rm -rf /storage/emulated/0/Android/data/$package_name/files/UE4Game/ShadowTrackerExtra/ShadowTrackerExtra/Saved/SaveGames/loginInfoFile.json 2>/dev/null
                rm -rf /storage/emulated/0/Android/data/$package_name/files/UE4Game/ShadowTrackerExtra/ShadowTrackerExtra/Saved/SaveGames/eLoginData.json 2>/dev/null
                echo -e "${red_start}SUCCESS${red_last}"
                sleep 1
                clear 
                echo -e "脚本启动时间为$now_time"
                ;;
            *)
                echo -e "${red_start}输入错误！请输入列表中的合法包名！${red_last}"
                sleep 1
                clear
                ;;
        esac
    }

#定义自定义终止进程函数*************************************
    diy_kill(){
        #自定义终止进程
        echo -e "自动终止常用APP，接下来请输入你自己所需终止的的应用包名"
        echo -e "${red_start}警告⚠️ 请勿输入数字！否则会误终止系统进程导致手机死机或重启！${red_last}"
        read -r package_name
        # 输入容错 禁止纯数字（POSIX兼容）
        if echo "$package_name" | grep -q '^[0-9]*$' 2>/dev/null; then
            echo -e "${red_start}错误：禁止输入纯数字！${red_last}"
            sleep 1
            clear
            return
        fi
        local DIYID=$(ps -ef | grep "$package_name" | grep -v grep | awk '{print $2}' 2>/dev/null)
        if [ -z "$DIYID"  ]; then
            echo -e "未找到该应用进程，或许你并没有打开此APP"
        else
            for pid in $DIYID; do
                if kill -9 $pid 2>/dev/null; then
                    echo -e "${red_start}终止成功！进程ID为$pid${red_last}"
                else
                    echo -e "${red_start}终止进程失败！进程ID为$pid${red_last}"
                fi
            done
        fi
        sleep 1
        clear
        echo -e "脚本启动时间为$now_time"
    }           

#PUBG自动清理函数********************************
    pubg_clear(){
        clear
        # 配置路径
        local NeiBu="/storage/emulated/0/Android/data/"
        local User="/data/user/0/"
        local Data="/data/data/"
        #定义ANSI转义码
        local ESC_SEQ="\x1b["
        local RESET_SEQ="${ESC_SEQ}0m"
        local COLOR_SEQ="${ESC_SEQ}38;5;"
        # 定义颜色代码
        local COLOR_RED="${COLOR_SEQ}9m"
        local COLOR_GREEN="${COLOR_SEQ}10m"
        local COLOR_YELLOW="${COLOR_SEQ}11m"
        local COLOR_BLUE="${COLOR_SEQ}12m"
        #模式选择 true=普通删除 false=强制删除
        local VAR="true"

        # 模式提示
        if [ "$VAR" = "true" ]; then
            echo -e "${COLOR_GREEN}\n当前为普通模式。${RESET_SEQ}"
        else
            echo -e "${COLOR_RED}\n当前为强制模式！${RESET_SEQ}"
        fi
        echo -e "${COLOR_YELLOW}游戏包名:${RESET_SEQ}"
        read -r B
        #错误处理
        if [ -z "$B" ]; then
            echo -e "${red_start}错误：包名不能为空！${red_last}"
            sleep 1
            return
        fi

        # 查找各类缓存路径 屏蔽错误
        local C=$(find "${NeiBu}${B}" "${User}${B}" "${Data}${B}" -iname '*Cache*' 2>/dev/null)
        local D=$(find "${NeiBu}${B}" "${User}${B}" "${Data}${B}" -iname '*log*' 2>/dev/null)
        local E=$(find "${NeiBu}${B}" "${User}${B}" "${Data}${B}" -iname '*tmp*' 2>/dev/null)
        local F=$(find "${NeiBu}${B}" "${User}${B}" "${Data}${B}" -iname '*temp*' 2>/dev/null)
        
        # 写入清理日志 修复换行问题
        local new_name="清理日志$(date +"%Y-%m-%d %H:%M:%S").txt"
        echo -e "Cache 路径：\n$C\n\nlog 路径：\n$D\n\ntmp 路径: \n$E\n\ntemp 路径: \n$F" > "$new_name" 2>/dev/null
        
        #模式判断执行清理
        if [ "$VAR" = "true" ]; then
            rm -f ${C} ${D} ${E} ${F} 2>/dev/null
        else
            rm -rf ${C} ${D} ${E} ${F} 2>/dev/null
        fi
        clear
        echo -e "${COLOR_GREEN}success！${RESET_SEQ}"
    }                        

#PUBG四服游客刷新************************************
    new_game(){
        clear    
        echo -e "请输入你要刷新游客的服务器"
        echo -e "${red_start}不要输入数字！请输入完整包名${red_last}"
        echo -e "1.com.tencent.ig\n2.com.pubg.krmobile\n3.com.rekoo.pubgm\n4.com.vng.pubgmobile\n5.com.tencent.igce"
   
        read -r choice
        # POSIX兼容case 替代数组包含判断
        case "$choice" in
            "com.tencent.ig"|"com.pubg.krmobile"|"com.rekoo.pubgm"|"com.vng.pubgmobile"|"com.tencent.igce")
                echo -e "${blue}${red_last}"
                clear
                # 时区检查
                local timezone=$( (timedatectl show --property=Timezone --value 2>/dev/null || date +%Z) | tr -d '\n' )
                if [ "$timezone" = "CST" ] || [ "$timezone" = "Asia/Shanghai" ]; then
                    echo -e "${yellow}请先更改时区：${red_last}"
                    echo -e "1.打开设置\n2.找到'日期和时间'->'时区'\n3.修改为香港时区"
                    exit 0
                fi
                # 清理并重建目录
                rm -rf /data/user/0/$choice/shared_prefs 2>/dev/null
                rm -rf /storage/emulated/0/Documents/ 2>/dev/null
                mkdir -p /data/user/0/$choice/shared_prefs 2>/dev/null
                chmod 777 /data/user/0/$choice/shared_prefs 2>/dev/null
                rm -rf /data/user/0/$choice/files 2>/dev/null

                # 生成device_id.xml
                local GUEST="/data/user/0/$choice/shared_prefs/device_id.xml"
                rm -rf $GUEST 2>/dev/null
                local uuid="$RANDOM$RANDOM-$RANDOM-$RANDOM-$RANDOM-$RANDOM$RANDOM$RANDOM"
                cat > $GUEST <<EOF
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="random"></string>
    <string name="install"></string>
    <string name="uuid">$uuid</string>
</map>
EOF

                # 清理各类文件
                rm -rf /data/user/0/$choice/databases 2>/dev/null
                rm -rf /data/media/0/Android/data/$choice/files/login-identifier.txt 2>/dev/null
                rm -rf /data/media/0/Android/data/$choice/files/UE4Game/ShadowTrackerExtra/ShadowTrackerExtra/Intermediate 2>/dev/null
                touch /data/media/0/Android/data/$choice/files/UE4Game/ShadowTrackerExtra/ShadowTrackerExtra/Intermediate 2>/dev/null
                rm -rf /data/media/0/Android/data/$choice/files/TGPA 2>/dev/null
                touch /data/media/0/Android/data/$choice/files/TGPA 2>/dev/null
                rm -rf /data/media/0/Android/data/$choice/files/ProgramBinaryCache 2>/dev/null
                touch /data/media/0/Android/data/$choice/files/ProgramBinaryCache 2>/dev/null

                # iptables屏蔽 兼容无iptables
                if command -v iptables >/dev/null 2>&1; then
                    iptables -I OUTPUT -d cloud.vmp.onezapp.com -j REJECT 2>/dev/null
                    iptables -I INPUT -s cloud.vmp.onezapp.com -j REJECT 2>/dev/null
                fi

                # 最终清理
                rm -rf /storage/emulated/0/Android/data/$choice/files/UE4Game/ShadowTrackerExtra/ShadowTrackerExtra/Saved/MMKV 2>/dev/null
                rm -rf /data/app/*/$choice-*/lib/arm64/libtgpa.so 2>/dev/null
                rm -rf /storage/emulated/0/Android/data/$choice/files/UE4Game/ShadowTrackerExtra/ShadowTrackerExtra/Saved/SaveGames/loginInfoFile.json 2>/dev/null
                rm -rf /storage/emulated/0/Android/data/$choice/files/UE4Game/ShadowTrackerExtra/ShadowTrackerExtra/Saved/SaveGames/eLoginData.json 2>/dev/null
                echo -e "${green}程序运行完成${red_last}"
                ;;
            *)
                echo -e "${red_start}输入错误！请输入列表中的合法包名！${red_last}"
                sleep 1
                ;;
        esac
        clear
    }

#Shell脚本加密函数************************************
    shell(){
        # 适配MT管理器：自动获取当脚本所在目录
        local SCRIPT_DIR=$(cd "$(dirname "$0")" || exit 1; pwd)
        # 步骤1：选择待加密的脚本文件
        echo "请输入当前目录下待加密的脚本文件名（比如：test.sh）："
        read -r INPUT_FILE
        local INPUT_PATH="${SCRIPT_DIR}/${INPUT_FILE}"
        # 检查文件是否存在
        if [ ! -f "$INPUT_PATH" ]; then
            echo -e "${red_start}错误：当前目录下找不到 ${INPUT_FILE}！${red_last}"
            exit 1
        fi
        # 步骤2：设置加密密码
        echo "请设置加密密码（后续运行加密文件需要输入）："
        read -r PASSWORD
        # 步骤3：设置输出文件名
        echo "请输入加密后的输出文件名（比如：encrypted.sh）："
        read -r OUTPUT_FILE
        local OUTPUT_PATH="${SCRIPT_DIR}/${OUTPUT_FILE}"
        # 检查openssl是否存在
        if ! command -v openssl >/dev/null 2>&1; then
            echo -e "${red_start}错误：未检测到openssl，无法加密！${red_last}"
            return
        fi
        # 生成随机盐值（AES加密必需）
        local SALT=$(openssl rand -hex 4 2>/dev/null)
        # 核心：生成自解密的加密文件
        cat > "$OUTPUT_PATH" <<EOF
#!/system/bin/sh
set -e
# 自解密配置
TARGET_SALT="${SALT}"
echo "请输入解密密码："
read -r DEC_PASS
# 解密并执行原脚本
echo "\$(cat <<'ENCRYPTED_BODY'
$(openssl enc -aes-256-cbc -salt -S "${SALT}" -pbkdf2 -iter 10000 -in "${INPUT_PATH}" -out - -k "${PASSWORD}" 2>/dev/null | base64 -w 0 2>/dev/null)
ENCRYPTED_BODY
)" | base64 -d 2>/dev/null | openssl enc -aes-256-cbc -d -salt -S "\${TARGET_SALT}" -pbkdf2 -iter 10000 -k "\${DEC_PASS}" 2>/dev/null | sh
EOF
        # 给加密文件添加执行权限
        chmod 755 "$OUTPUT_PATH" 2>/dev/null
        # 提示完成
        echo -e "${green}加密成功！${red_last}"
        echo "原文件：${INPUT_PATH}"
        echo "加密文件：${OUTPUT_PATH}"
        echo "运行 ${OUTPUT_FILE} 即可自动解密并执行原脚本"
        sleep 1
    }

#更新日志函数**********************************************
    Log(){
        clear
        echo "正在加载更新日志 请等待...."
        sleep 1
        clear
        local log_path="/storage/emulated/0/Download/Shell/更新日志.txt"
        if [ -f "$log_path" ]; then
            cat "$log_path"
        else
            echo -e "${red_start}错误：更新日志文件不存在！${red_last}"
            echo -e "文件路径：$log_path"
        fi
    }

#设备信息查询函数**********************************************
    Android(){
        echo "设备信息加载中......"
        sleep 1
        echo "[+]设备型号: $(getprop ro.product.model 2>/dev/null)"
        echo "[+]设备厂商: $(getprop ro.product.manufacturer 2>/dev/null)"
        echo "[+]设备品牌: $(getprop ro.product.brand 2>/dev/null)"
        echo "[+]Android版本: $(getprop ro.build.version.release 2>/dev/null)"
        echo "[+]Android ID: $(settings get secure android_id 2>/dev/null)"
        echo "[+]设备序列号: $(getprop ro.serialno 2>/dev/null)"
        echo "[+]API级别: $(getprop ro.build.version.sdk 2>/dev/null)"
        echo "[+]安全补丁: $(getprop ro.build.version.security_patch 2>/dev/null)"
        echo "[+]内核版本: $(cat /proc/version 2>/dev/null | cut -d' ' -f3 2>/dev/null)"        
    }

#设备缓存清理函数**********************************************
    clear_cache(){
        echo -e "此脚本为豆包Ai联合制作的清理缓存工具"
        echo -e "使用Mt扩展环境执行效果更佳"
        echo -e "准备读取data数据目录"
        sleep 3
        local DATA_DIR="/storage/emulated"
        local total_clean=0
        echo "===== 读取${DATA_DIR}目录内容（含大小） ====="
        if [ ! -d "${DATA_DIR}" ]; then
            echo -e "${red_start}错误：${DATA_DIR}不存在！${red_last}"
            return
        fi
        ls -lh "${DATA_DIR}" 2>/dev/null
        sleep 3
        clear
        echo -e "开始清理缓存......"
        sleep 1
        clear
        echo -e "\n===== 清理cache文件夹（排除软链接） ====="
        # 清理cache 兼容特殊文件名（POSIX）
        find "${DATA_DIR}" -type d -name "cache" -print0 2>/dev/null | while IFS= read -r -d '' cache_dir; do
            # 统计清理前大小
            local pre_size=$(du -sb "${cache_dir}/" 2>/dev/null | awk '{print $1}')
            pre_size=${pre_size:-0}
            if [ "$pre_size" -eq 0 ]; then
                echo "跳过空文件夹：${cache_dir}"
                continue
            fi
            # 强制删除内容
            rm -rf "${cache_dir}/"* "${cache_dir}/".* 2>/dev/null
            # 统计清理后大小
            local post_size=$(du -sb "${cache_dir}/" 2>/dev/null | awk '{print $1}')
            post_size=${post_size:-0}
            # 计算释放大小
            local release=$((pre_size - post_size))
            total_clean=$((total_clean + release))
            # 格式化显示
            local pre_fmt=$(numfmt --to=iec --suffix=B $pre_size 2>/dev/null)
            local rel_fmt=$(numfmt --to=iec --suffix=B $release 2>/dev/null)
            echo "清理：${cache_dir} | 原大小：${pre_fmt} | 实际释放：${rel_fmt}"
        done
        # 最终统计
        local fmt_total=$(numfmt --to=iec --suffix=B $total_clean 2>/dev/null)
        echo -e "\n===== 清理完成！总释放空间：${green}${fmt_total}${red_last} ====="
    }

#全局120帧解锁函数**********************************************
    120zhen(){
        # 全局120帧解锁·全安卓通用·全应用生效
        echo -e "本程序由豆包ai提供技术支持 官网doubao.com"
        sleep 3
        clear
        # 加载系统命令路径
        export PATH=/system/bin:/system/xbin:/sbin:/vendor/bin:/odm/bin:/product/bin:$PATH
        echo "正在开启全局120帧..."
        sleep 1
        # 全局强制高刷
        settings put global force_refresh_rate 1 2>/dev/null
        settings put global user_refresh_rate 1 2>/dev/null
        # 锁死120Hz
        settings put system min_refresh_rate 120 2>/dev/null
        settings put system peak_refresh_rate 120 2>/dev/null
        settings put system default_refresh_rate 120 2>/dev/null
        # 关闭MIUI智能降帧
        settings put system refresh_rate_mode 2 2>/dev/null
        settings put global miui_smart_fps_enable 0 2>/dev/null
        settings put global miui_refresh_rate_enable 0 2>/dev/null
        settings put global app_compat_framerate_enable 0 2>/dev/null
        echo -e "120帧配置完成 正在添加电量与性能白名单"
        sleep 1
        # POSIX兼容循环 替代Bash数组
        for app in \
            "com.ss.android.ugc.aweme" \
            "com.smile.gifmaker" \
            "com.tencent.tmgp.sgame" \
            "com.tencent.tmgp.dfm" \
            "com.netease.party" \
            "com.tuyoo.doudizhu.android3d"
        do
            dumpsys deviceidle whitelist + $app 2>/dev/null
        done
        echo -e "出现added代表添加成功！"
        echo -e "${green}Success！${red_last}"
        # 重启系统UI生效
        pkill -9 com.android.systemui 2>/dev/null
        echo "全局120帧开启完成！"
        echo "所有应用已强制锁定120帧，无降帧风险"
        echo "全程不修改只读系统属性，无砖机风险"
        sleep 2
    }

#脚本主菜单***********************************************
    clear
    sleep 1
    while true; do
        clear
        echo -e "脚本启动时间为$now_time"
        echo -e "${bg_purple}此脚本为综合功能脚本，编写此脚本纯娱乐"
        echo -e "只是想锻炼一下自己的技术，学习更多的shell脚本知识"
        echo -e "编写者为纯纯纯新手小白 | 仅供娱乐使用"
        echo -e "因为学业 加上不知道想更新什么 更新频率会降低${red_last}"
        echo -e "当前版本v2.7.4 | 更新时间:26.4.6"
        echo -e "============================================="
        sleep 1
        echo -e "${yellow}请根据你的需要输入对应数字：${red_last}"
        echo -e "1. 全局120刷新率解锁\n2. 自动终止常用进程\n3. 手动输入包名终止进程"
        echo -e "4. 重启当前设备\n5. PUBG过300秒限制\n6. 自定义文件目录备份"
        echo -e "7. 清理游戏ano缓存(自动执行)\n8. 全游戏缓存一键清理\n9. PUBG四服游客刷新"
        echo -e "10. Shell脚本加密\n11. 查看更新日志\n12. 查询设备详细信息"
        echo -e "13. 清理设备全局缓存\n100. 退出脚本"
        echo -e "============================================="
        sleep 1
        read -r choice
        case $choice in
            1)
                120zhen
                ;;
            2)
                kill_app
                ;;
            3)
                diy_kill
                ;;
            4)
                reboot_system
                ;;
            5)           
                kill_game
                ;;
            6)  
                backup
                ;;  
            7)
                echo -e "${red_start}调用函数成功！即将开始执行${red_last}"
                sleep 1
                kill_ano
                clear
                echo -e "脚本执行时间:$now_time"
                sleep 1
                ;; 
            8) 
                clear 
                echo -e "${red_start}正在启动一键清理..........${red_last}"
                sleep 1
                pubg_clear
                clear          
                ;;
            9)
                clear
                new_game
                sleep 1
                clear
                ;;
            10)
                clear
                shell
                ;;
            11)
                Log
                ;;
            12)
                clear
                Android              
                ;;        
            13)
                clear_cache
                ;;                
            100)
                clear        
                echo -e "${green}[+]脚本已安全退出...${red_last}"
                exit 0
                ;;
            *)
                clear
                echo -e "${red_start}输入错误！请输入菜单中的有效数字！${red_last}"
                sleep 1
                ;;
        esac
        # 执行完功能后暂停，方便查看结果
        echo -e "\n${yellow}按任意键返回主菜单...${red_last}"
        read -n 1 -s
    done            
}

#==================== 完整卡密验证+云更新+心跳模块 ====================
# 读取之前的计数
count=$(getprop persist.sys.script.count)
if [ -z "$count" ]; then
  count=0
fi

# 次数+1
count=$((count + 1))

# 存回系统属性（不生成文件）
setprop persist.sys.script.count "$count"

# 输出
echo "脚本已运行 $count 次"
read -p "使用卡密验证请输入yes 否则直接回车: " input
if [ "$input" = "yes" ]; then
# ====================== 开发者核心配置项 ======================
# 【接口配置】- 对接云端验证/更新接口的必备参数
# 应用唯一标识（即后台应用ID或者 API Key）
API_KEY="6194a4117a4c034acd7aaac459fd7556"

# 【版本配置】- 用于和云端版本比对，判断是否需要更新
# 本地脚本当前版本号
CURRENT_VERSION="2.7.4"

# 【更新行为配置】- 新版本替换后是否自动执行
# 取值说明：
#   1 = 更新完成后，自动重启脚本运行
#   0 = 更新完成后，退出脚本，需手动重启执行
AUTO_EXEC_AFTER_UPDATE="1"

# 【心跳验证配置】- 后台保活验证的参数设置
# 心跳验证间隔时间（单位：秒），默认5分钟=300秒
# 注意：取值不可低于30秒，否则会被云端判定为异常请求封禁
HEARTBEAT_INTERVAL=300

# 服务器无响应/网络异常时的重试次数
# 注意：无需手动修改，保持默认即可
HEARTBEAT_RETRY=3

# ======================开发者配置完成-下方代码无需修改======================
mt_read() {
    echo "$1"
    read CARD_KEY
}

API_URL_UPDATE=$(echo "aHR0cHM6Ly9tLmI2dy5jbi9hcGkvYjZ3YXBpeWd4LnBocA==" | base64 -d)
API_URL_VERIFY=$(echo "aHR0cHM6Ly9tLmI2dy5jbi9hcGkvYjZ3YXBpa2V5LnBocA==" | base64 -d)
REPORT_URL=$(echo "aHR0cHM6Ly9tLmI2dy5jbi9hcGkvc2IucGhw" | base64 -d)
SIGN_KEY="必6网.免费的云更新验证系统官方网站部分浏览器显示有风险可以换个浏览器-浏览器搜索b6w.cn"
DEVICE_FILE="/data/local/tmp/.device_code.txt"
BACKUP_DEVICE_FILE="./.device_code.txt"
CARD_KEY_MAIN_FILE="/data/local/tmp/.saved_card_key.txt"
CARD_KEY_BACKUP_FILE="./.saved_card_key.txt"
RETRY_INTERVAL=3

get_device_code() {
    local hardware_id=""
    if [ -z "$hardware_id" ] && [ -f "/sys/class/android_usb/android0/iSerial" ]; then
        hardware_id=$(cat /sys/class/android_usb/android0/iSerial 2>/dev/null | tr -d ' \n\r')
    fi
    if [ -z "$hardware_id" ] && [ -f "/proc/cpuinfo" ]; then
        hardware_id=$(grep -i 'serial' /proc/cpuinfo 2>/dev/null | head -n1 | awk -F: '{print $2}' | tr -d ' \n\r')
    fi
    if [ -z "$hardware_id" ] && command -v getprop &>/dev/null; then
        hardware_id=$(getprop ro.serialno 2>/dev/null | tr -d ' \n\r')
        [ -z "$hardware_id" ] && hardware_id=$(getprop ro.boot.serialno 2>/dev/null | tr -d ' \n\r')
    fi
    if [ -z "$hardware_id" ] && [ -f "/sys/class/bluetooth/hci0/address" ]; then
        hardware_id=$(cat /sys/class/bluetooth/hci0/address 2>/dev/null | tr -d ':\n\r')
    fi
    if [ -z "$hardware_id" ] && [ -f "/sys/class/net/wlan0/address" ]; then
        hardware_id=$(cat /sys/class/net/wlan0/address 2>/dev/null | tr -d ':\n\r')
    fi
    if [ -z "$hardware_id" ]; then
        if [ -f "$BACKUP_DEVICE_FILE" ]; then
            hardware_id=$(cat "$BACKUP_DEVICE_FILE" 2>/dev/null | tr -d ' \n\r')
        elif [ -f "$DEVICE_FILE" ]; then
            hardware_id=$(cat "$DEVICE_FILE" 2>/dev/null | tr -d ' \n\r')
        else
            hardware_id=$(date +%s | md5sum | head -c 16)
        fi
    fi
    local fixed_code="$hardware_id"
    [ ${#fixed_code} -gt 32 ] && fixed_code="${fixed_code:0:32}"
    if [ ${#fixed_code} -lt 32 ]; then
        fixed_code=$(printf "%-32s" "$fixed_code" | tr ' ' '0')
    fi
    if ! echo "$fixed_code" > "$BACKUP_DEVICE_FILE" 2>/dev/null; then
        if echo "$fixed_code" > "$DEVICE_FILE" 2>/dev/null; then
            DEVICE_FILE="$DEVICE_FILE"
        else
            echo "[警告] 设备码文件写入失败，临时生效" >&2
        fi
    else
        DEVICE_FILE="$BACKUP_DEVICE_FILE"
    fi
    chmod 600 "$DEVICE_FILE" 2>/dev/null
    echo "$fixed_code"
}

DEVICE_CODE=$(get_device_code)
[ -z "$DEVICE_CODE" ] && { echo "设备码生成失败" >&2; exit 1; }

request_with_retry() {
    local url="$1"
    local data="$2"
    local retry_count=1
    while true; do
        local response=$(curl -s --connect-timeout 10 -X POST "$url" -H "Content-Type: application/json" -d "$data")
        if [ $? -eq 0 ] && [ -n "$response" ]; then
            echo "$response"
            return 0
        fi
        echo "[重试] 接口请求失败（第$retry_count次），$RETRY_INTERVAL秒后重试..."
        sleep $RETRY_INTERVAL
        retry_count=$((retry_count + 1))
    done
}
extract_field() {
    local key="$1"
    local json="$2"
    local single_json=$(echo "$json" | sed ':a;N;$!ba;s/\n/###NL###/g')
    local value=$(echo "$single_json" | sed -n "s/.*\"$key\":\"//;s/\".*//p")
    echo "$value" | sed 's/###NL###/\n/g' | sed 's/\\\\n/\n/g'
}

check_update() {
    echo "===== 开始云更新检查 ====="
    local verify_data='{"action":"verify_api_key", "api_key":"'$API_KEY'"}'
    local verify_response=$(request_with_retry "$API_URL_UPDATE" "$verify_data")
    local app_id=$(extract_field "app_id" "$verify_response")

    if [ -z "$app_id" ]; then
        local error_msg=$(extract_field "error" "$verify_response")
        echo "[错误] 更新验证失败：$error_msg"
        return 1
    fi
    echo "[成功] 应用ID：$app_id"

    local config_data='{"action":"get_config", "app_id":"'$app_id'"}'
    local config_response=$(request_with_retry "$API_URL_UPDATE" "$config_data")

    local announcement=$(extract_field "announcement" "$config_response")
    local latest_version=$(extract_field "latest_version" "$config_response")
    local update_url=$(extract_field "update_url" "$config_response")

    local force_update=$(echo "$config_response" | sed ':a;N;$!ba;s/\n//g' | sed -n 's/.*"force_update"[ ]*:[ ]*\([truefalse]\{4,5\}\)[,}].*/\1/p')
    [ -z "$force_update" ] && force_update="false"

    local force_update_cn="否"
    [ "$force_update" = "true" ] && force_update_cn="是"

    echo -e "\n[配置信息]:"
    echo -n "  公告内容："
    if [ -n "$announcement" ]; then
        echo -e "\n$announcement"
    else
        echo "无公告"
    fi
    echo "  当前版本：$CURRENT_VERSION（本地）"
    echo "  最新版本：$latest_version（云端）"
    echo "  是否强制更新：$force_update_cn"
    echo "  开发者更新配置-更新后自动执行：$( [ "$AUTO_EXEC_AFTER_UPDATE" = "1" ] && echo "是" || echo "否" )"

    update_url=$(echo "$update_url" | sed 's/\\\//\//g')

    if [ "$latest_version" != "$CURRENT_VERSION" ] && [ -n "$update_url" ] && [ "$latest_version" != "" ]; then
        echo -e "\n[发现新版本] $latest_version"
        if ! command -v curl &> /dev/null; then
            echo "[错误] 缺少curl工具，请安装后重试"
            exit 1
        fi

        if [ "$force_update" = "true" ]; then
            echo "[强制更新] 必须更新才能继续使用！"
            update_action=1
        else
            echo "[非强制更新] 发现新版本，是否更新？（1=更新，0=不更新，默认0）"
            mt_read "请输入选择（1/0）："
            [ -z "$CARD_KEY" ] && user_choice=0 || user_choice=$CARD_KEY
            if [ "$user_choice" -eq 1 ]; then
                echo "用户选择：执行更新"
                update_action=1
            else
                echo "用户选择：不更新，继续执行后续流程"
                update_action=0
                rm -f "$new_file_path" 2>/dev/null
                return 0
            fi
        fi

        if [ $update_action -eq 1 ]; then
            local script_path=$(cd "$(dirname "$0")" || exit; pwd)
            local script_name=$(basename "$0")
            local new_file_path="${script_path}/temp_update_file"

            while true; do
                if curl -fL "$update_url" -o "$new_file_path" &> /dev/null; then
                    break
                fi
                echo "[重试] 更新文件下载失败，$RETRY_INTERVAL秒后重试..."
                sleep $RETRY_INTERVAL
            done

            local file_ext=$(echo "$update_url" | awk -F. '{print $NF}' | tr 'A-Z' 'a-z' | sed 's/^[ 	]*//;s/[ 	]*$//')
            echo "[更新文件信息] 后缀：$file_ext"

            if [ "$file_ext" = "zip" ]; then
                echo "[更新处理] 识别ZIP文件，生成唯一文件名（保留所有旧文件）"
                local random_str=$(date +%s%N | md5sum | head -c 8)
                local zip_file_name="${script_name%.sh}-${latest_version}-${random_str}.zip"
                local zip_file_path="${script_path}/${zip_file_name}"
            
                if [ -f "$zip_file_path" ]; then
                    echo "[提示] 极端情况：文件名已存在，重新生成随机字符..."
                    random_str=$(date +%s%N | md5sum | head -c 8)
                    zip_file_name="${script_name%.sh}-${latest_version}-${random_str}.zip"
                    zip_file_path="${script_path}/${zip_file_name}"
                fi

                if cat "$new_file_path" > "$0"; then
                    mv -f "$0" "$zip_file_path"
                    echo "[成功] ZIP更新完成：$zip_file_path"
                    echo "[提示] 所有旧版本ZIP文件已完整保留，新文件通过版本号+随机字符区分"
                    echo "[提示] ZIP文件无法自动执行，已退出"
                    rm -f "$new_file_path"
                    exit 0
                else
                    echo "[错误] ZIP文件内容替换失败"
                    rm -f "$new_file_path"
                    exit 1
                fi
            else
                echo "[更新处理] 识别非ZIP文件，覆盖更新并准备自动执行"
                local backup_script_path="${script_path}/${script_name}.bak"
                cp -f "$0" "$backup_script_path" 2>/dev/null
                if cat "$new_file_path" > "$0"; then
                    chmod +x "$0"
                    echo "[成功] 脚本更新至 $latest_version（旧脚本已备份为 ${script_name}.bak）"
                    rm -f "$new_file_path"
                    if [ "$AUTO_EXEC_AFTER_UPDATE" = "1" ]; then
                        echo "按配置：立即自动执行更新后的脚本..."
                        exec sh "$0"
                        echo "[警告] 自动执行触发失败，请手动运行 $0"
                        exit 1
                    else
                        echo "按配置：不自动执行，请手动重启 $0"
                        exit 0
                    fi
                else
                    echo "[错误] 非ZIP文件更新失败，恢复旧脚本..."
                    cp -f "$backup_script_path" "$0" 2>/dev/null
                    rm -f "$new_file_path" "$backup_script_path"
                    exit 1
                fi
            fi
        fi
    else
        if [ "$latest_version" = "$CURRENT_VERSION" ]; then
            echo -e "\n[状态] 本地版本（$CURRENT_VERSION）与云端版本（$latest_version）一致，无需更新"
        elif [ -z "$update_url" ]; then
            echo -e "\n[状态] 虽有新版本（$latest_version），但云端未配置更新链接，无法更新"
        else
            echo -e "\n[状态] 当前已是最新版本"
        fi
    fi
    echo -e "\n===== 更新检查完成 ====="
}

decode_unicode() {
    local str="$1"
    while echo "$str" | grep -q '\\u[0-9a-fA-F]\{4\}'; do
        local unicode=$(echo "$str" | sed -n 's/.*\(\\u[0-9a-fA-F]\{4\}\).*/\1/p')
        local hex=${unicode#\\u}
        local dec=$((16#$hex))
        local char=$(printf "\\$(printf '%03o' "$dec")")
        str=$(echo "$str" | sed "s/${unicode}/${char}/")
    done
    echo "$str"
}

generate_sign() {
    local data="$1"
    local salt="$2"
    local timestamp="$3"
    echo -n "${data}${salt}${timestamp}${SIGN_KEY}" | md5sum | awk '{print $1}'
}

report_tampering() {
    local request_params="$1"
    local tampered_response="$2"
    local timestamp="$3"
    local client_ip=$(curl -s --connect-timeout 5 http://icanhazip.com 2>/dev/null || curl -s --connect-timeout 5 http://ip.cn/ip 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' || echo "未知IP")
    client_ip=$(echo "$client_ip" | tr -d '\n\r')

    req_escaped=$(echo "$request_params" | sed 's/\\/\\\\/g')
    resp_escaped=$(echo "$tampered_response" | sed 's/\\/\\\\/g')
    req_escaped=$(echo "$req_escaped" | sed 's/"/\\"/g')
    resp_escaped=$(echo "$resp_escaped" | sed 's/"/\\"/g')
    req_escaped=$(echo "$req_escaped" | sed ':a;N;$!ba;s/\n/\\n/g')
    resp_escaped=$(echo "$resp_escaped" | sed ':a;N;$!ba;s/\n/\\n/g')
    req_escaped=$(echo "$req_escaped" | sed 's/\r/\\r/g; s/\t/\\t/g')
    resp_escaped=$(echo "$resp_escaped" | sed 's/\r/\\r/g; s/\t/\\t/g')

    report_data="{\"ip\":\"$client_ip\",\"timestamp\":\"$timestamp\",\"request_params\":\"$req_escaped\",\"tampered_response\":\"$resp_escaped\"}"
    report_result=$(curl -s --connect-timeout 10 -X POST "$REPORT_URL" -H "Content-Type: application/json" -d "$report_data")
    result_msg=$(echo "$report_result" | sed -n 's/.*"message":"\([^"]*\)".*/\1/p' | decode_unicode)
    echo "数据已记录上传结果：${result_msg:-篡改数据已上传}"
}

verify_card_key() {
    echo -e "\n===== 开始卡密验证 ====="
    local CARD_KEY=""
    if [ -f "$CARD_KEY_BACKUP_FILE" ]; then
        CARD_KEY=$(cat "$CARD_KEY_BACKUP_FILE" 2>/dev/null | tr -d ' \n\r')
        [ -n "$CARD_KEY" ] && echo "[自动登录] 从当前目录读取到卡密，自动验证..."
    fi
    if [ -z "$CARD_KEY" ] && [ -f "$CARD_KEY_MAIN_FILE" ]; then
        CARD_KEY=$(cat "$CARD_KEY_MAIN_FILE" 2>/dev/null | tr -d ' \n\r')
        [ -n "$CARD_KEY" ] && echo "[自动登录] 从主路径读取到卡密，自动验证..."
    fi

    while true; do
        if [ -z "$CARD_KEY" ]; then
            mt_read "请输入卡密："
            [ -z "$CARD_KEY" ] && { echo "卡密不能为空，请重新输入"; continue; }
        fi

        local TIMESTAMP=$(date +%s)
        local REQUEST_PARAMS=$(printf '{"api_key":"%s","key":"%s","device_code":"%s","timestamp":"%s"}' "$API_KEY" "$CARD_KEY" "$DEVICE_CODE" "$TIMESTAMP")
        local RESPONSE=$(request_with_retry "$API_URL_VERIFY" "$REQUEST_PARAMS")

        local CODE=$(echo "$RESPONSE" | sed -n 's/.*"code"[ 	]*:[ 	]*\([0-9]*\).*/\1/p; s/.*"code"[ 	]*:[ 	]*\([0-9]*\),.*/\1/p' | head -n1)
        local MESSAGE_RAW=$(echo "$RESPONSE" | sed -n 's/.*"message"[ 	]*:"\([^"]*\)".*/\1/p; s/.*"message"[ 	]*:"\([^"]*\)",.*/\1/p' | head -n1)
        local MESSAGE=$(decode_unicode "$MESSAGE_RAW")
        local DATA=$(echo "$RESPONSE" | sed -n 's/.*"data"[ 	]*:"\([^"]*\)".*/\1/p' | head -n1)
        local SALT=$(echo "$RESPONSE" | sed -n 's/.*"salt"[ 	]*:"\([^"]*\)".*/\1/p' | head -n1)
        local SERVER_SIGN=$(echo "$RESPONSE" | sed -n 's/.*"sign"[ 	]*:"\([^"]*\)".*/\1/p' | head -n1)

        if [ "$CODE" -eq 200 ] && [ -n "$DATA" ] && [ -n "$SALT" ] && [ -n "$SERVER_SIGN" ]; then
            local CLIENT_SIGN=$(generate_sign "$DATA" "$SALT" "$TIMESTAMP")
            if [ "$CLIENT_SIGN" != "$SERVER_SIGN" ]; then
                echo "验证失败：数据被篡改.请勿非法破解.严重的提交至公安机关处理"
                report_tampering "$REQUEST_PARAMS" "$RESPONSE" "$TIMESTAMP"
                CARD_KEY=""
                continue
            fi

            local RAW_DATA=$(echo -n "$DATA" | base64 -d 2>/dev/null)
            local EXPIRES_AT=$(echo "$RAW_DATA" | sed -n 's/.*"expires_at"[ 	]*:"\([^"]*\)".*/\1/p; s/.*"expires_at":"\([^"]*\)".*/\1/p' | head -n1 | tr -d ' \n\r}')
            local USED_DEVICES=$(echo "$RAW_DATA" | sed -n 's/.*"used_devices"[ 	]*:\([0-9]*\).*/\1/p; s/.*"used_devices":\([0-9]*\).*/\1/p' | head -n1 | tr -d ' \n\r,}')
            local MAX_DEVICES=$(echo "$RAW_DATA" | sed -n 's/.*"max_devices"[ 	]*:\([0-9]*\).*/\1/p; s/.*"max_devices":\([0-9]*\).*/\1/p' | head -n1 | tr -d ' \n\r,}')

            if [ -n "$EXPIRES_AT" ] && [ -n "$USED_DEVICES" ] && [ -n "$MAX_DEVICES" ]; then
                if echo "$CARD_KEY" > "$CARD_KEY_BACKUP_FILE" 2>/dev/null; then
                    chmod 600 "$CARD_KEY_BACKUP_FILE"
                    echo "[自动登录] 卡密已保存到当前目录（$CARD_KEY_BACKUP_FILE），下次自动验证"
                elif echo "$CARD_KEY" > "$CARD_KEY_MAIN_FILE" 2>/dev/null; then
                    chmod 600 "$CARD_KEY_MAIN_FILE"
                    echo "[自动登录] 卡密已保存到主路径（$CARD_KEY_MAIN_FILE），下次自动验证"
                else
                    echo "[警告] 卡密保存失败，下次需重新输入" >&2
                fi
                export GLOBAL_CARD_KEY="$CARD_KEY"
                export GLOBAL_EXPIRES_AT="$EXPIRES_AT"
                export GLOBAL_USED_DEVICES="$USED_DEVICES"
                export GLOBAL_MAX_DEVICES="$MAX_DEVICES"
                break
            else
                echo "验证失败：数据不完整，请重新输入"
                CARD_KEY=""
            fi
        else
            [ -z "$MESSAGE" ] && MESSAGE="未知错误"
            echo "验证失败：$MESSAGE，请重新输入"
            CARD_KEY=""
            [ -f "$CARD_KEY_MAIN_FILE" ] && rm -f "$CARD_KEY_MAIN_FILE"
            [ -f "$CARD_KEY_BACKUP_FILE" ] && rm -f "$CARD_KEY_BACKUP_FILE"
        fi
    done
}

heartbeat_verify() {
    echo -e "\n===== 心跳验证已启动（间隔$HEARTBEAT_INTERVAL秒） ====="
    while true; do
        sleep $HEARTBEAT_INTERVAL
        echo -e "\n[心跳] （$(date "+%Y-%m-%d %H:%M:%S")）"

        local card_key="$GLOBAL_CARD_KEY"
        local device_code="$DEVICE_CODE"
        [ -z "$card_key" ] || [ -z "$device_code" ] && { echo "[心跳] 卡密/设备码缺失，强制中断脚本"; exit 1; }

        local TIMESTAMP=$(date +%s)
        local REQUEST_PARAMS=$(printf '{"api_key":"%s","key":"%s","device_code":"%s","timestamp":"%s"}' "$API_KEY" "$card_key" "$device_code" "$TIMESTAMP")
        local retry_count=1
        local RESPONSE=""
        while [ $retry_count -le $HEARTBEAT_RETRY ]; do
            RESPONSE=$(curl -s --connect-timeout 10 -X POST "$API_URL_VERIFY" -H "Content-Type: application/json" -d "$REQUEST_PARAMS")
            [ $? -eq 0 ] && [ -n "$RESPONSE" ] && break
            echo "[心跳重试] 请求失败（第$retry_count次），$RETRY_INTERVAL秒后重试..."
            sleep $RETRY_INTERVAL
            retry_count=$((retry_count + 1))
        done

        [ -z "$RESPONSE" ] && { echo "[心跳] 服务器无响应，本次跳过"; continue; }

        local CODE=$(echo "$RESPONSE" | sed -n 's/.*"code"[ 	]*:[ 	]*\([0-9]*\).*/\1/p; s/.*"code"[ 	]*:[ 	]*\([0-9]*\),.*/\1/p' | head -n1)
        local MESSAGE_RAW=$(echo "$RESPONSE" | sed -n 's/.*"message"[ 	]*:"\([^"]*\)".*/\1/p; s/.*"message"[ 	]*:"\([^"]*\)",.*/\1/p' | head -n1)
        local MESSAGE=$(decode_unicode "$MESSAGE_RAW")

        [ "$CODE" -eq 200 ] && echo "[心跳] 验证成功" || { echo "[心跳] 卡密验证失败：$MESSAGE"; echo "[心跳] 强制中断脚本运行"; exit 1; }
    done
}

start_heartbeat_in_background() {
    heartbeat_verify &
    HEARTBEAT_PID=$!
    trap 'kill $HEARTBEAT_PID 2>/dev/null' EXIT
}
#注：源代码执行期间，心跳会在后台每隔$HEARTBEAT_INTERVAL秒自动验证
check_update
verify_card_key
echo -e "\n卡密验证成功"
echo "到期时间：$GLOBAL_EXPIRES_AT"
echo "设备限制：已用$GLOBAL_USED_DEVICES台，共$GLOBAL_MAX_DEVICES台"

start_heartbeat_in_background
    # 执行更新检查并启动主程序    
    main
else
    # 跳过卡密验证，直接启动主程序
    main
fi
