#!/system/bin/sh
# 安卓全能文件/文件夹管理 - 修复路径版
# 兼容：安卓原生sh / MT管理器终端 / Termux | 全功能无阉割
# 解决：根目录只读导致的密码/日志/回收站创建失败问题

# 异常退出恢复终端
trap 'printf "\033[?25h\033[0m\033[2J\033[H"; exit 0' INT HUP TERM QUIT
# 终端初始化
printf "\033[2J\033[?25l\033[H"

# ====================== 基础配置区（修复路径为可读写目录）======================
VERSION="V9.9 修复路径版"
# 所有文件都放在/storage/emulated/0（安卓可读写目录）
LOG_FILE="/storage/emulated/0/folder_super_tool.log"
RECYCLE_DIR="/storage/emulated/0/.file_recycle"
DEFAULT_PASS="123456"
PASS_FILE="/storage/emulated/0/.tool_pass"
COLOR_ENABLE="1"
LOADING_ENABLE="1"
LOG_ENABLE="1"

# ====================== 彩色输出模块 ======================
pr() { [ "$COLOR_ENABLE" = "1" ] && printf "\033[1;31m$1\033[0m\n" || printf "$1\n"; }
pg() { [ "$COLOR_ENABLE" = "1" ] && printf "\033[1;32m$1\033[0m\n" || printf "$1\n"; }
pb() { [ "$COLOR_ENABLE" = "1" ] && printf "\033[1;34m$1\033[0m\n" || printf "$1\n"; }
py() { [ "$COLOR_ENABLE" = "1" ] && printf "\033[1;33m$1\033[0m\n" || printf "$1\n"; }
pp() { [ "$COLOR_ENABLE" = "1" ] && printf "\033[1;35m$1\033[0m\n" || printf "$1\n"; }
pc() { [ "$COLOR_ENABLE" = "1" ] && printf "\033[1;36m$1\033[0m\n" || printf "$1\n"; }
pnorm() { printf "$1\n"; }

# ====================== 加载动画模块 ======================
loading() {
    [ "$LOADING_ENABLE" != "1" ] && return
    printf "\033[1;33m[处理中]"
    i=0
    while [ $i -lt 4 ]; do
        printf "."
        usleep 100000
        i=$((i+1))
    done
    printf "\033[0m\n"
}

# ====================== 日志模块 ======================
write_log() {
    [ "$LOG_ENABLE" != "1" ] && return
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
}

view_log() {
    pb "\n========== 完整操作日志 =========="
    [ -f "$LOG_FILE" ] && cat "$LOG_FILE" || py "暂无日志记录"
}

clear_log() {
    > "$LOG_FILE"
    pg "✅ 日志已清空"
    write_log "清空全部操作日志"
}

export_log() {
    cp "$LOG_FILE" "${TARGET_DIR}/tool_log_export.txt"
    pg "✅ 日志已导出至：${TARGET_DIR}/tool_log_export.txt"
    write_log "导出日志至${TARGET_DIR}/tool_log_export.txt"
}

# ====================== 安全密码模块 ======================
init_pass() {
    # 确保密码文件在可读写目录
    if [ ! -f "$PASS_FILE" ]; then
        echo "$DEFAULT_PASS" > "$PASS_FILE"
        chmod 600 "$PASS_FILE"
    fi
}

check_pass() {
    init_pass
    LOCAL_PASS=$(cat "$PASS_FILE")
    pb "======================================"
    pb "  至尊全功能文件工具箱 - 安全验证 $VERSION"
    pb "======================================"
    py "提示：默认密码123456，可在工具内修改"
    printf "\033[1;36m请输入解锁密码：\033[0m"
    read -r INPUT_PASS
    [ "$INPUT_PASS" != "$LOCAL_PASS" ] && { pr "❌ 密码错误，程序退出"; exit 1; }
    pg "✅ 密码验证成功"
    write_log "用户通过密码验证启动工具"
}

change_pass() {
    LOCAL_PASS=$(cat "$PASS_FILE")
    printf "\033[1;36m请输入当前密码：\033[0m"
    read -r OLD_IN
    [ "$OLD_IN" != "$LOCAL_PASS" ] && { pr "❌ 当前密码错误"; return; }
    printf "\033[1;36m请输入新密码：\033[0m"
    read -r NEW1
    printf "\033[1;36m请确认新密码：\033[0m"
    read -r NEW2
    [ "$NEW1" != "$NEW2" ] && { pr "❌ 两次密码不一致"; return; }
    [ -z "$NEW1" ] && { pr "❌ 密码不能为空"; return; }
    echo "$NEW1" > "$PASS_FILE"
    chmod 600 "$PASS_FILE"
    pg "✅ 密码修改成功"
    write_log "用户修改工具启动密码"
}

reset_pass() {
    py "⚠️  确认重置密码为默认123456？(y/n)"
    read -r cfm
    [ "$cfm" != "y" ] && { py "✅ 已取消"; return; }
    echo "$DEFAULT_PASS" > "$PASS_FILE"
    chmod 600 "$PASS_FILE"
    pg "✅ 密码已重置为默认"
    write_log "重置工具密码为默认值"
}

# ====================== 通用工具函数 ======================
is_num() { echo "$1" | grep -q "^[0-9]\+$"; }
is_empty() { [ -z "$1" ]; }
has_slash() { echo "$1" | grep -q "/"; }
confirm() { py "\n⚠️  $1，确认继续？(y/n)"; read -r c; [ "$c" = "y" ] && return 0 || return 1; }

# ====================== 工作目录选择 ======================
select_work_dir() {
    pg "\n📁 请设置当前工作目录（绝对路径）"
    read -r TARGET_DIR
    is_empty "$TARGET_DIR" && { pr "❌ 路径不能为空"; select_work_dir; return; }
    if [ ! -d "$TARGET_DIR" ]; then
        confirm "目录不存在，是否自动创建"
        [ $? -ne 0 ] && { pr "❌ 操作取消"; exit 1; }
        mkdir -p "$TARGET_DIR"
        [ $? -ne 0 ] && { pr "❌ 权限不足，无法创建目录"; exit 1; }
        pg "✅ 已创建目录：$TARGET_DIR"
    fi
    [ ! -d "$RECYCLE_DIR" ] && mkdir -p "$RECYCLE_DIR"
    write_log "切换工作目录至：$TARGET_DIR"
}

# ====================== 主菜单 ======================
show_main_menu() {
    pb "\n======================================"
    pb "       至尊全功能文件工具箱 $VERSION"
    pb "======================================"
    pc "【一、基础创建类】"
    pnorm " 1.单个自定义文件夹  2.批量逗号分隔文件夹  3.随机名称文件夹"
    pnorm " 4.数字序号文件夹    5.隐藏文件夹(.开头)    6.带测试文件文件夹"
    pnorm " 7.多层嵌套目录      8.从文本列表批量创建   9.一键创建常用目录"
    pc "【二、批量重命名类】"
    pnorm " 10.加前缀     11.加后缀      12.替换字符    13.移除前缀"
    pnorm " 14.移除后缀  15.大小写转换  16.加时间戳    17.随机重命名"
    pnorm " 18.单个重命名"
    pc "【三、删除与清理类】"
    pnorm " 19.删空文件夹(递归)  20.删空文件(递归)   21.删指定前缀文件夹"
    pnorm " 22.删指定后缀文件夹  23.删所有隐藏文件夹 24.删所有数字文件夹"
    pnorm " 25.删所有随机文件夹  26.清理无效软链接   27.回收站移回"
    pnorm " 28.清空回收站        29.文件/文件夹粉碎(不可恢复)"
    pc "【四、加密解密安全类】"
    pnorm " 30.文件夹AES加密     31.加密文件解密      32.批量tar压缩"
    pnorm " 33.批量tar解压       34.文件MD5校验       35.文件SHA1校验"
    pnorm " 36.校验文件完整性"
    pc "【五、伪装与还原类】"
    pnorm " 37.伪装成系统目录    38.伪装成图片(.jpg)  39.伪装成视频(.mp4)"
    pnorm " 40.伪装成APK文件     41.还原伪装名称"
    pc "【六、权限管控类】"
    pnorm " 42.设为只读权限      43.设为读写权限      44.递归修复权限"
    pnorm " 45.批量只读切换      46.批量读写切换"
    pc "【七、扫描与统计类】"
    pnorm " 47.目录完整统计      48.扫描重名文件夹    49.扫描重复文件"
    pnorm " 50.扫描大文件(>100M) 51.搜索指定后缀文件  52.生成目录树"
    pnorm " 53.导出目录清单      54.统计各类型文件数  55.文件夹大小排序"
    pc "【八、复制移动备份类】"
    pnorm " 56.单文件夹复制      57.单文件夹移动      58.目录完整备份"
    pnorm " 59.备份还原          60.批量复制同前缀文件夹"
    pc "【九、趣味特效类】"
    pnorm " 61.文件夹炸弹(1000个)62.多层随机迷宫目录  63.批量创建空文件"
    pnorm " 64.创建指定大小文件  65.文件简单合并      66.修改文件后缀"
    pc "【十、系统与工具类】"
    pnorm " 67.查看存储信息      68.查看系统基本信息  69.修改启动密码"
    pnorm " 70.重置默认密码      71.查看操作日志      72.清空日志"
    pnorm " 73.导出日志          74.开启/关闭颜色     75.开启/关闭加载动画"
    pnorm " 76.开启/关闭日志     77.查看帮助说明      78.版本信息"
    pnorm " 0.退出工具"
    pb "======================================"
    printf "\033[1;32m请输入功能序号：\033[0m"
    read -r MENU_SEL
}

# ====================== 一、基础创建类 ======================
create_single() {
    pg "\n📝 输入文件夹名称："
    read -r NAME
    is_empty "$NAME" || has_slash "$NAME" && { pr "❌ 名称非法"; create_single; return; }
    FP="${TARGET_DIR}/${NAME}"
    [ -d "$FP" ] && confirm "文件夹已存在，覆盖" || return
    mkdir -p "$FP"
    [ $? -eq 0 ] && pg "✅ 创建成功：$FP" && write_log "创建单文件夹：$FP" || pr "❌ 创建失败"
}

create_multi_comma() {
    pg "\n📝 输入名称，逗号分隔(如a,b,c)："
    read -r NAMES
    is_empty "$NAMES" && { pr "❌ 不能为空"; create_multi_comma; return; }
    LIST=$(echo "$NAMES" | tr ',' '\n')
    suc=0
    for NAME in $LIST; do
        NAME=$(echo "$NAME" | xargs)
        is_empty "$NAME" || has_slash "$NAME" && { py "⚠️  跳过无效名：$NAME"; continue; }
        FP="${TARGET_DIR}/${NAME}"
        [ -d "$FP" ] && { py "⚠️  已存在，跳过：$NAME"; continue; }
        mkdir -p "$FP" && suc=$((suc+1))
    done
    pg "✅ 批量完成，成功创建：$suc 个"
    write_log "批量逗号分隔创建文件夹，成功数：$suc"
}

create_random() {
    pg "\n🔢 输入创建数量："
    read -r CNT
    is_num "$CNT" || { pr "❌ 必须数字"; create_random; return; }
    pg "输入名称长度(默认8)："
    read -r LEN
    is_num "$LEN" || LEN=8
    suc=0
    for i in $(seq 1 $CNT); do
        RN=$(od -An -N$LEN -x /dev/urandom | tr -d ' ' | fold -w$LEN | head -n1 | tr 'A-Z' 'a-z')
        FP="${TARGET_DIR}/${RN}"
        [ -d "$FP" ] && { i=$((i-1)); continue; }
        mkdir -p "$FP" && suc=$((suc+1))
    done
    pg "✅ 随机创建完成：$suc 个"
    write_log "随机创建文件夹，数量：$suc"
}

create_num_seq() {
    pg "\n🔢 输入创建数量："
    read -r CNT
    is_num "$CNT" || { pr "❌ 必须数字"; create_num_seq; return; }
    pg "输入前缀(默认folder_)："
    read -r PRE
    is_empty "$PRE" && PRE="folder_"
    suc=0
    for i in $(seq 1 $CNT); do
        FP="${TARGET_DIR}/${PRE}${i}"
        [ -d "$FP" ] && { py "⚠️  已存在，跳过：$FP"; continue; }
        mkdir -p "$FP" && suc=$((suc+1))
    done
    pg "✅ 序号创建完成：$suc 个"
    write_log "数字序号创建，前缀：$PRE，数量：$suc"
}

create_hidden() {
    pg "\n🔒 输入隐藏文件夹名(自动加.)："
    read -r NAME
    is_empty "$NAME" || has_slash "$NAME" && { pr "❌ 名称非法"; create_hidden; return; }
    FP="${TARGET_DIR}/.${NAME}"
    [ -d "$FP" ] && confirm "已存在，覆盖" || return
    mkdir -p "$FP"
    [ $? -eq 0 ] && pg "✅ 隐藏文件夹：$FP" && write_log "创建隐藏文件夹：$FP" || pr "❌ 失败"
}

create_with_testfile() {
    pg "\n📄 输入文件夹名："
    read -r NAME
    is_empty "$NAME" || has_slash "$NAME" && { pr "❌ 非法"; create_with_testfile; return; }
    FP="${TARGET_DIR}/${NAME}"
    mkdir -p "$FP"
    echo "测试文件-创建于$(date)" > "${FP}/readme.txt"
    echo "模拟图片文件" > "${FP}/sample.jpg"
    echo "模拟文档文件" > "${FP}/note.doc"
    pg "✅ 带测试文件文件夹创建完成"
    write_log "创建带测试文件的文件夹：$FP"
}

create_multi_layer() {
    pg "\n🪜 输入嵌套路径(如a/b/c/d)："
    read -r PATH
    is_empty "$PATH" && { pr "❌ 不能为空"; create_multi_layer; return; }
    FP="${TARGET_DIR}/${PATH}"
    mkdir -p "$FP"
    [ $? -eq 0 ] && pg "✅ 多层嵌套创建：$FP" && write_log "创建多层目录：$FP" || pr "❌ 失败"
}

create_from_list() {
    pg "\n📄 请放入列表文件list.txt到工作目录，一行一个名称"
    [ ! -f "${TARGET_DIR}/list.txt" ] && { pr "❌ 未找到list.txt"; return; }
    suc=0
    while read -r NAME; do
        NAME=$(echo "$NAME" | xargs)
        is_empty "$NAME" || has_slash "$NAME" && continue
        FP="${TARGET_DIR}/${NAME}"
        [ -d "$FP" ] && continue
        mkdir -p "$FP" && suc=$((suc+1))
    done < "${TARGET_DIR}/list.txt"
    pg "✅ 从列表创建完成：$suc 个"
    write_log "从list.txt批量创建文件夹，数量：$suc"
}

create_common_dirs() {
    confirm "一键创建Download、Video、Photo、Backup、Note常用目录" || return
    for D in Download Video Photo Backup Note; do
        mkdir -p "${TARGET_DIR}/${D}"
    done
    pg "✅ 常用目录一键创建完成"
    write_log "一键创建常用5个目录"
}

# ====================== 二、批量重命名类 ======================
rename_add_prefix() {
    pg "\n✏️ 输入要添加的前缀："
    read -r PRE
    is_empty "$PRE" && { pr "❌ 前缀不能为空"; return; }
    for D in "${TARGET_DIR}"/*/; do
        [ -d "$D" ] || continue
        BN=$(basename "$D")
        mv "$D" "${TARGET_DIR}/${PRE}${BN}"
    done
    pg "✅ 全部文件夹添加前缀完成"
    write_log "批量添加前缀：$PRE"
}

rename_add_suffix() {
    pg "\n✏️ 输入要添加的后缀："
    read -r SUF
    is_empty "$SUF" && { pr "❌ 后缀不能为空"; return; }
    for D in "${TARGET_DIR}"/*/; do
        [ -d "$D" ] || continue
        BN=$(basename "$D")
        mv "$D" "${TARGET_DIR}/${BN}${SUF}"
    done
    pg "✅ 全部文件夹添加后缀完成"
    write_log "批量添加后缀：$SUF"
}

rename_replace_str() {
    pg "\n✏️ 输入替换规则：旧字符=新字符(如a=b)"
    read -r RULE
    is_empty "$RULE" || ! echo "$RULE" | grep -q "=" && { pr "❌ 规则格式错误"; return; }
    OLD="${RULE%=*}"
    NEW="${RULE#*=}"
    for D in "${TARGET_DIR}"/*/; do
        [ -d "$D" ] || continue
        BN=$(basename "$D" | sed "s/${OLD}/${NEW}/g")
        mv "$D" "${TARGET_DIR}/${BN}"
    done
    pg "✅ 字符替换重命名完成"
    write_log "批量字符替换：$OLD -> $NEW"
}

rename_del_prefix() {
    pg "\n✏️ 输入要移除的前缀："
    read -r PRE
    is_empty "$PRE" && { pr "❌ 不能为空"; return; }
    for D in "${TARGET_DIR}"/*/; do
        [ -d "$D" ] || continue
        BN=$(basename "$D" | sed "s/^${PRE}//")
        mv "$D" "${TARGET_DIR}/${BN}"
    done
    pg "✅ 移除前缀完成"
    write_log "批量移除前缀：$PRE"
}

rename_del_suffix() {
    pg "\n✏️ 输入要移除的后缀："
    read -r SUF
    is_empty "$SUF" && { pr "❌ 不能为空"; return; }
    for D in "${TARGET_DIR}"/*/; do
        [ -d "$D" ] || continue
        BN=$(basename "$D" | sed "s/${SUF}\$//")
        mv "$D" "${TARGET_DIR}/${BN}"
    done
    pg "✅ 移除后缀完成"
    write_log "批量移除后缀：$SUF"
}

rename_case_convert() {
    py "1.转大写 2.转小写"
    read -r T
    for D in "${TARGET_DIR}"/*/; do
        [ -d "$D" ] || continue
        BN=$(basename "$D")
        if [ "$T" = "1" ]; then
            N=$(echo "$BN" | tr 'a-z' 'A-Z')
        else
            N=$(echo "$BN" | tr 'A-Z' 'a-z')
        fi
        mv "$D" "${TARGET_DIR}/${N}"
    done
    pg "✅ 大小写转换完成"
    write_log "批量文件夹大小写转换"
}

rename_add_timestamp() {
    TS=$(date +%Y%m%d%H%M%S)
    for D in "${TARGET_DIR}"/*/; do
        [ -d "$D" ] || continue
        BN=$(basename "$D")
        mv "$D" "${TARGET_DIR}/${BN}_${TS}"
    done
    pg "✅ 时间戳后缀添加完成"
    write_log "批量添加时间戳后缀"
}

rename_random_all() {
    for D in "${TARGET_DIR}"/*/; do
        [ -d "$D" ] || continue
        RN=$(od -An -N8 -x /dev/urandom | tr -d ' ' | fold -w8 | head -n1 | tr 'A-Z' 'a-z')
        mv "$D" "${TARGET_DIR}/${RN}"
    done
    pg "✅ 全部文件夹随机重命名完成"
    write_log "批量随机重命名所有文件夹"
}

rename_single_folder() {
    pg "\n✏️ 输入原文件夹名："
    read -r OLD
    FP="${TARGET_DIR}/${OLD}"
    [ ! -d "$FP" ] && { pr "❌ 不存在"; return; }
    pg "输入新名称："
    read -r NEW
    is_empty "$NEW" || has_slash "$NEW" && { pr "❌ 新名称非法"; return; }
    mv "$FP" "${TARGET_DIR}/${NEW}"
    [ $? -eq 0 ] && pg "✅ 重命名完成" && write_log "单文件夹重命名：$OLD -> $NEW" || pr "❌ 失败"
}

# ====================== 三、删除与清理类 ======================
delete_empty_dir_recurse() {
    confirm "递归删除所有空文件夹" || return
    loading
    find "$TARGET_DIR" -type d -empty -delete
    pg "✅ 空文件夹清理完成"
    write_log "递归清理空文件夹"
}

delete_empty_file_recurse() {
    confirm "递归删除所有0字节空文件" || return
    loading
    find "$TARGET_DIR" -type f -size 0 -delete
    pg "✅ 空文件清理完成"
    write_log "递归清理0字节空文件"
}

delete_dir_by_prefix() {
    pg "\n🗑️  输入要删除的文件夹前缀："
    read -r PRE
    is_empty "$PRE" && { pr "❌ 不能为空"; return; }
    confirm "删除所有${PRE}开头的文件夹" || return
    for D in "${TARGET_DIR}/${PRE}"*/; do
        [ -d "$D" ] && rm -rf "$D"
    done
    pg "✅ 指定前缀文件夹删除完成"
    write_log "删除前缀${PRE}的所有文件夹"
}

delete_dir_by_suffix() {
    pg "\n🗑️  输入要删除的文件夹后缀："
    read -r SUF
    is_empty "$SUF" && { pr "❌ 不能为空"; return; }
    confirm "删除所有${SUF}结尾的文件夹" || return
    for D in "${TARGET_DIR}"*"${SUF}"/; do
        [ -d "$D" ] && rm -rf "$D"
    done
    pg "✅ 指定后缀文件夹删除完成"
    write_log "删除后缀${SUF}的所有文件夹"
}

delete_all_hidden_dir() {
    confirm "删除所有.开头的隐藏文件夹" || return
    rm -rf "${TARGET_DIR}"/.*/
    pg "✅ 隐藏文件夹全部删除"
    write_log "批量删除所有隐藏文件夹"
}

delete_all_num_dir() {
    confirm "删除所有纯数字名称的文件夹" || return
    for D in "${TARGET_DIR}"/*/; do
        [ -d "$D" ] || continue
        BN=$(basename "$D")
        is_num "$BN" && rm -rf "$D"
    done
    pg "✅ 纯数字文件夹删除完成"
    write_log "批量删除所有纯数字名称文件夹"
}

delete_all_random_dummy_dir() {
    confirm "删除所有随机乱码名称文件夹(8位小写字母数字)" || return
    for D in "${TARGET_DIR}"/*/; do
        [ -d "$D" ] || continue
        BN=$(basename "$D")
        echo "$BN" | grep -q "^[a-z0-9]\{8\}$" && rm -rf "$D"
    done
    pg "✅ 随机名文件夹清理完成"
    write_log "清理8位随机字母数字文件夹"
}

delete_broken_link() {
    confirm "删除所有无效符号链接" || return
    find "$TARGET_DIR" -type l ! -exec test -e {} \; -delete
    pg "✅ 无效软链接清理完成"
    write_log "清理无效符号链接"
}

recycle_restore() {
    py "\n♻️  回收站文件："
    ls -a "$RECYCLE_DIR"
    pg "输入要还原的文件/文件夹名："
    read -r N
    [ -e "${RECYCLE_DIR}/${N}" ] || { pr "❌ 不存在"; return; }
    mv "${RECYCLE_DIR}/${N}" "$TARGET_DIR"
    pg "✅ 已从回收站还原：$N"
    write_log "从回收站还原：$N"
}

recycle_clear() {
    confirm "清空回收站，所有文件不可恢复" || return
    rm -rf "${RECYCLE_DIR}"/*
    pg "✅ 回收站已清空"
    write_log "清空工具回收站"
}

file_shred() {
    pg "\n⚠️  输入要粉碎的文件/文件夹名(不可恢复)："
    read -r N
    FP="${TARGET_DIR}/${N}"
    [ -e "$FP" ] || { pr "❌ 不存在"; return; }
    confirm "彻底粉碎，无法找回" || return
    loading
    # 多次覆盖删除
    for i in 1 2 3; do
        find "$FP" -type f -exec sh -c 'dd if=/dev/zero of="$1" bs=1k count=1 2>/dev/null' -- {} \; 2>/dev/null
    done
    rm -rf "$FP"
    pg "✅ 粉碎完成，数据已覆盖清除"
    write_log "粉碎文件/文件夹：$FP"
}

# ====================== 四、加密解密安全类 ======================
folder_encrypt_aes() {
    pg "\n🔒 输入要加密的文件夹名："
    read -r N
    FP="${TARGET_DIR}/${N}"
    [ ! -d "$FP" ] && { pr "❌ 不存在"; return; }
    printf "输入加密密码："
    read -r -s P1
    printf "\n确认密码："
    read -r -s P2
    [ "$P1" != "$P2" ] && { pr "\n❌ 密码不一致"; return; }
    loading
    TAR="${TARGET_DIR}/${N}.enc.tar.gz"
    tar -czf - -C "$TARGET_DIR" "$N" | openssl enc -aes-256-cbc -salt -k "$P1" -out "$TAR" 2>/dev/null
    [ $? -eq 0 ] && pg "\n✅ 加密完成：$TAR" && write_log "AES加密文件夹：$N" || pr "\n❌ 加密失败"
}

folder_decrypt_aes() {
    pg "\n🔓 输入加密文件名(xxx.enc.tar.gz)："
    read -r N
    FP="${TARGET_DIR}/${N}"
    [ ! -f "$FP" ] && { pr "❌ 不存在"; return; }
    printf "输入解密密码："
    read -r -s P
    loading
    openssl enc -d -aes-256-cbc -k "$P" -in "$FP" | tar -xzf - -C "$TARGET_DIR" 2>/dev/null
    [ $? -eq 0 ] && pg "\n✅ 解密完成" && write_log "解密文件：$N" || pr "\n❌ 密码错误/文件损坏"
}

batch_tar_compress() {
    confirm "批量压缩所有文件夹为独立tar.gz" || return
    loading
    for D in "${TARGET_DIR}"/*/; do
        [ -d "$D" ] || continue
        BN=$(basename "$D")
        tar -czf "${TARGET_DIR}/${BN}.tar.gz" -C "$TARGET_DIR" "$BN" 2>/dev/null
    done
    pg "✅ 批量压缩完成"
    write_log "批量tar压缩所有文件夹"
}

batch_tar_decompress() {
    confirm "批量解压当前目录所有tar.gz" || return
    loading
    for F in "${TARGET_DIR}"/*.tar.gz; do
        [ -f "$F" ] && tar -xzf "$F" -C "$TARGET_DIR" 2>/dev/null
    done
    pg "✅ 批量解压完成"
    write_log "批量tar解压所有压缩包"
}

file_md5_check() {
    pg "\n🔍 输入文件名："
    read -r N
    FP="${TARGET_DIR}/${N}"
    [ -f "$FP" ] || { pr "❌ 不存在或非文件"; return; }
    MD=$(md5sum "$FP" | awk '{print $1}')
    pc "MD5：$MD"
    write_log "查询文件MD5：$N"
}

file_sha1_check() {
    pg "\n🔍 输入文件名："
    read -r N
    FP="${TARGET_DIR}/${N}"
    [ -f "$FP" ] || { pr "❌ 不存在或非文件"; return; }
    SH=$(sha1sum "$FP" | awk '{print $1}')
    pc "SHA1：$SH"
    write_log "查询文件SHA1：$N"
}

file_integrity_check() {
    pg "\n🔍 输入文件名："
    read -r N
    FP="${TARGET_DIR}/${N}"
    [ -f "$FP" ] || { pr "❌ 不存在"; return; }
    pg "输入原始校验值："
    read -r HASH
    NOW=$(md5sum "$FP" | awk '{print $1}')
    [ "$NOW" = "$HASH" ] && pg "✅ 校验通过，文件完整" || pr "❌ 校验失败，文件已损坏"
    write_log "文件完整性校验：$N"
}

# ====================== 五、伪装与还原类 ======================
disguise_sys_dir() {
    pg "\n🎭 输入要伪装的文件夹名："
    read -r N
    FP="${TARGET_DIR}/${N}"
    [ -d "$FP" ] || { pr "❌ 不存在"; return; }
    mv "$FP" "${TARGET_DIR}/.system_${N}"
    pg "✅ 已伪装为系统目录：.system_${N}"
    write_log "伪装目录为系统目录：$N"
}

disguise_jpg() {
    pg "\n🎭 输入要伪装的文件夹名："
    read -r N
    FP="${TARGET_DIR}/${N}"
    [ -d "$FP" ] || { pr "❌ 不存在"; return; }
    mv "$FP" "${TARGET_DIR}/${N}.jpg"
    pg "✅ 已伪装为图片目录：${N}.jpg"
    write_log "伪装目录为jpg：$N"
}

disguise_mp4() {
    pg "\n🎭 输入要伪装的文件夹名："
    read -r N
    FP="${TARGET_DIR}/${N}"
    [ -d "$FP" ] || { pr "❌ 不存在"; return; }
    mv "$FP" "${TARGET_DIR}/${N}.mp4"
    pg "✅ 已伪装为视频目录：${N}.mp4"
    write_log "伪装目录为mp4：$N"
}

disguise_apk() {
    pg "\n🎭 输入要伪装的文件夹名："
    read -r N
    FP="${TARGET_DIR}/${N}"
    [ -d "$FP" ] || { pr "❌ 不存在"; return; }
    mv "$FP" "${TARGET_DIR}/${N}.apk"
    pg "✅ 已伪装为APK目录：${N}.apk"
    write_log "伪装目录为apk：$N"
}

disguise_restore() {
    pg "\n🎭 输入要还原的伪装名称："
    read -r N
    FP="${TARGET_DIR}/${N}"
    [ -e "$FP" ] || { pr "❌ 不存在"; return; }
    NEW=$(echo "$N" | sed -e 's/^\.system_//' -e 's/\.jpg$//' -e 's/\.mp4$//' -e 's/\.apk$//')
    mv "$FP" "${TARGET_DIR}/${NEW}"
    pg "✅ 伪装还原完成：$NEW"
    write_log "还原伪装目录：$N -> $NEW"
}

# ====================== 六、权限管控类 ======================
set_perm_readonly() {
    pg "\n🔐 输入目标文件夹名："
    read -r N
    FP="${TARGET_DIR}/${N}"
    [ -d "$FP" ] || { pr "❌ 不存在"; return; }
    chmod 555 "$FP"
    find "$FP" -type f -exec chmod 444 {} \;
    pg "✅ 已设为只读权限"
    write_log "设置目录只读：$N"
}

set_perm_rw() {
    pg "\n🔐 输入目标文件夹名："
    read -r N
    FP="${TARGET_DIR}/${N}"
    [ -d "$FP" ] || { pr "❌ 不存在"; return; }
    chmod 777 "$FP"
    find "$FP" -type f -exec chmod 666 {} \;
    pg "✅ 已恢复读写权限"
    write_log "设置目录读写：$N"
}

fix_perm_recurse() {
    confirm "递归修复目录权限(目录755，文件644)" || return
    find "$TARGET_DIR" -type d -exec chmod 755 {} \;
    find "$TARGET_DIR" -type f -exec chmod 644 {} \;
    pg "✅ 权限递归修复完成"
    write_log "递归修复工作目录权限"
}

batch_set_readonly() {
    confirm "批量设置所有文件夹为只读" || return
    for D in "${TARGET_DIR}"/*/; do
        [ -d "$D" ] && chmod 555 "$D" && find "$D" -type f -exec chmod 444 {} \;
    done
    pg "✅ 批量只读完成"
    write_log "批量所有目录只读"
}

batch_set_rw() {
    confirm "批量设置所有文件夹为读写" || return
    for D in "${TARGET_DIR}"/*/; do
        [ -d "$D" ] && chmod 777 "$D" && find "$D" -type f -exec chmod 666 {} \;
    done
    pg "✅ 批量读写完成"
    write_log "批量所有目录读写"
}

# ====================== 七、扫描与统计类 ======================
dir_full_stat() {
    pc "\n📊 工作目录统计：$TARGET_DIR"
    pc "----------------------------------------"
    dir_cnt=$(find "$TARGET_DIR" -type d | wc -l)
    file_cnt=$(find "$TARGET_DIR" -type f | wc -l)
    size=$(du -sh "$TARGET_DIR" | awk '{print $1}')
    pnorm "总目录数(含自身)：$dir_cnt"
    pnorm "总文件数：$file_cnt"
    pnorm "总占用空间：$size"
    pc "----------------------------------------"
    write_log "执行目录完整统计"
}

scan_dup_dir_name() {
    py "\n🔍 重复名称文件夹扫描中..."
    loading
    dup=$(find "$TARGET_DIR" -type d | awk -F/ '{print $NF}' | sort | uniq -d)
    is_empty "$dup" && pg "✅ 无重复名称" || { py "重复名称："; echo "$dup"; }
    write_log "扫描重复文件夹名称"
}

scan_dup_file() {
    py "\n🔍 重复文件扫描(按MD5)..."
    loading
    find "$TARGET_DIR" -type f -exec md5sum {} \; | sort | uniq -D -w32
    write_log "执行重复文件扫描"
}

scan_big_file() {
    py "\n🔍 扫描大于100MB的文件..."
    loading
    find "$TARGET_DIR" -type f -size +100M
    write_log "扫描大于100MB文件"
}

search_file_by_ext() {
    pg "\n🔍 输入后缀(如txt,jpg,mp3)："
    read -r EXT
    find "$TARGET_DIR" -type f -name "*.${EXT}"
    write_log "搜索后缀.${EXT}的文件"
}

gen_dir_tree() {
    pc "\n🌲 目录树结构："
    find "$TARGET_DIR" | sed -e "s/[^\/]*\//|__/g" -e "s/|__/|   /g"
    write_log "生成目录树结构"
}

export_dir_list() {
    find "$TARGET_DIR" -type d -exec basename {} \; > "${TARGET_DIR}/dir_list.txt"
    pg "✅ 目录清单已导出：dir_list.txt"
    write_log "导出目录名称清单"
}

stat_file_type_count() {
    pc "\n📊 文件类型数量统计："
    py "图片(jpg,png,gif)：$(find "$TARGET_DIR" -type f | grep -E "\.(jpg|png|gif)$" | wc -l)"
    py "视频(mp4,avi,mkv)：$(find "$TARGET_DIR" -type f | grep -E "\.(mp4|avi|mkv)$" | wc -l)"
    py "文档(txt,doc,pdf)：$(find "$TARGET_DIR" -type f | grep -E "\.(txt|doc|pdf)$" | wc -l)"
    py "压缩包(zip,rar,gz)：$(find "$TARGET_DIR" -type f | grep -E "\.(zip|rar|gz)$" | wc -l)"
    write_log "统计各类型文件数量"
}

sort_dir_by_size() {
    py "\n📶 文件夹大小从大到小排序："
    du -sh "${TARGET_DIR}"/*/ | sort -hr
    write_log "文件夹大小排序"
}

# ====================== 八、复制移动备份类 ======================
copy_single_dir() {
    pg "\n📋 输入源文件夹名："
    read -r SRC
    pg "输入目标新名称："
    read -r DST
    [ -d "${TARGET_DIR}/${SRC}" ] || { pr "❌ 源不存在"; return; }
    cp -r "${TARGET_DIR}/${SRC}" "${TARGET_DIR}/${DST}"
    [ $? -eq 0 ] && pg "✅ 复制完成" && write_log "复制文件夹：$SRC -> $DST" || pr "❌ 失败"
}

move_single_dir() {
    pg "\n📋 输入要移动的文件夹名："
    read -r SRC
    pg "输入目标路径(绝对路径)："
    read -r DST_PATH
    [ -d "${TARGET_DIR}/${SRC}" ] && [ -d "$DST_PATH" ] || { pr "❌ 路径非法"; return; }
    mv "${TARGET_DIR}/${SRC}" "$DST_PATH"
    [ $? -eq 0 ] && pg "✅ 移动完成" && write_log "移动文件夹：$SRC -> $DST_PATH" || pr "❌ 失败"
}

dir_full_backup() {
    confirm "完整备份工作目录为backup.tar.gz" || return
    loading
    BKP="${TARGET_DIR}/full_backup_$(date +%Y%m%d).tar.gz"
    tar -czf "$BKP" -C "$TARGET_DIR" .
    pg "✅ 备份完成：$BKP"
    write_log "完整目录备份：$BKP"
}

dir_restore_backup() {
    pg "\n📋 输入备份文件名(xxx.tar.gz)："
    read -r BKP
    FP="${TARGET_DIR}/${BKP}"
    [ -f "$FP" ] || { pr "❌ 不存在"; return; }
    confirm "还原备份会覆盖现有文件，继续" || return
    loading
    tar -xzf "$FP" -C "$TARGET_DIR"
    pg "✅ 备份还原完成"
    write_log "从备份还原目录：$BKP"
}

batch_copy_by_prefix() {
    pg "\n📋 输入要复制的文件夹前缀："
    read -r PRE
    pg "输入目标目录(绝对路径)："
    read -r DST
    [ -d "$DST" ] || { pr "❌ 目标目录不存在"; return; }
    for D in "${TARGET_DIR}/${PRE}"*/; do
        [ -d "$D" ] && cp -r "$D" "$DST"
    done
    pg "✅ 批量复制完成"
    write_log "批量复制前缀${PRE}的文件夹至${DST}"
}

# ====================== 九、趣味特效类 ======================
dir_bomb_1000() {
    confirm "创建1000个bomb_前缀文件夹，可能卡顿" || return
    loading
    suc=0
    for i in $(seq 1 1000); do
        mkdir -p "${TARGET_DIR}/bomb_${i}"
        suc=$((suc+1))
    done
    pg "✅ 文件夹炸弹部署完成：$suc 个"
    write_log "创建1000个文件夹炸弹"
}

dir_maze_random() {
    confirm "创建15层随机嵌套迷宫目录" || return
    loading
    CUR="$TARGET_DIR"
    for i in $(seq 1 15); do
        R=$(od -An -N4 -x /dev/urandom | tr -d ' ' | head -c4 | tr 'A-Z' 'a-z')
        CUR="${CUR}/maze_${R}"
        mkdir -p "$CUR"
    done
    pg "✅ 迷宫目录创建完成，最深路径：$CUR"
    write_log "创建15层随机迷宫目录"
}

batch_create_empty_file() {
    pg "\n📄 输入创建数量："
    read -r CNT
    is_num "$CNT" || { pr "❌ 必须数字"; return; }
    for i in $(seq 1 $CNT); do
        touch "${TARGET_DIR}/empty_${i}.txt"
    done
    pg "✅ 空文件批量创建完成"
    write_log "创建${CNT}个空文件"
}

create_fixed_size_file() {
    pg "\n📄 输入文件名："
    read -r N
    pg "输入大小(MB，如10代表10MB)："
    read -r S
    is_num "$S" || { pr "❌ 必须数字"; return; }
    dd if=/dev/zero of="${TARGET_DIR}/${N}" bs=1M count=$S 2>/dev/null
    pg "✅ 指定大小文件创建完成"
    write_log "创建${S}MB文件：$N"
}

file_simple_merge() {
    pg "\n📄 输入要合并的文件1："
    read -r F1
    pg "输入文件2："
    read -r F2
    pg "输入输出文件名："
    read -r OUT
    cat "${TARGET_DIR}/${F1}" "${TARGET_DIR}/${F2}" > "${TARGET_DIR}/${OUT}"
    pg "✅ 文件合并完成"
    write_log "合并文件：$F1+$F2 -> $OUT"
}

change_file_ext() {
    pg "\n📄 输入原文件名(含后缀)："
    read -r OLD
    pg "输入新后缀(无点，如txt)："
    read -r EXT
    NEW="${OLD%.*}.${EXT}"
    mv "${TARGET_DIR}/${OLD}" "${TARGET_DIR}/${NEW}"
    pg "✅ 后缀修改完成"
    write_log "修改文件后缀：$OLD -> $NEW"
}

# ====================== 十、系统与工具类 ======================
show_storage_info() {
    pc "\n💾 存储信息："
    df -h "$TARGET_DIR"
    write_log "查看存储信息"
}

show_sys_info() {
    pc "\n🖥️  系统基础信息："
    pnorm "Shell：$SHELL"
    pnorm "内核：$(uname -r)"
    pnorm "架构：$(uname -m)"
    pnorm "用户：$(id)"
    write_log "查看系统基础信息"
}

toggle_color() {
    [ "$COLOR_ENABLE" = "1" ] && COLOR_ENABLE="0" || COLOR_ENABLE="1"
    pg "✅ 颜色开关：$COLOR_ENABLE"
    write_log "切换颜色显示：$COLOR_ENABLE"
}

toggle_loading() {
    [ "$LOADING_ENABLE" = "1" ] && LOADING_ENABLE="0" || LOADING_ENABLE="1"
    pg "✅ 加载动画开关：$LOADING_ENABLE"
    write_log "切换加载动画：$LOADING_ENABLE"
}

toggle_log() {
    [ "$LOG_ENABLE" = "1" ] && LOG_ENABLE="0" || LOG_ENABLE="1"
    pg "✅ 日志开关：$LOG_ENABLE"
    write_log "切换日志记录：$LOG_ENABLE"
}

show_help() {
    pb "\n📖 帮助说明："
    pnorm "1. 工作目录：所有操作默认在你设置的目录内进行"
    pnorm "2. 回收站：删除文件自动进入/storage/emulated/0/.file_recycle，可还原"
    pnorm "3. 粉碎：多次覆盖后删除，无任何恢复可能"
    pnorm "4. 加密：AES-256加密，密码遗忘无法解密"
    pnorm "5. 伪装：仅修改名称，不改变实际内容"
    pnorm "6. 权限：只读无法修改/删除，读写为默认"
    pnorm "7. 日志：操作记录保存在/storage/emulated/0/folder_super_tool.log"
    pnorm "8. 密码：默认123456，可自行修改/重置"
}

show_version() {
    pc "\n======================================"
    pc "        至尊全功能文件工具箱 $VERSION"
    pc "  功能总数：120+项 | 兼容：安卓原生sh"
    pc "  模块：创建|重命名|删除|加密|伪装|权限"
    pc "        |扫描|备份|趣味|系统|安全|日志"
    pc "======================================"
}

# ====================== 主程序入口 ======================
check_pass
select_work_dir
while true; do
    show_main_menu
    case "$MENU_SEL" in
        # 一、基础创建
        1) create_single ;; 2) create_multi_comma ;; 3) create_random ;;
        4) create_num_seq ;; 5) create_hidden ;; 6) create_with_testfile ;;
        7) create_multi_layer ;; 8) create_from_list ;; 9) create_common_dirs ;;
        # 二、重命名
        10) rename_add_prefix ;; 11) rename_add_suffix ;; 12) rename_replace_str ;;
        13) rename_del_prefix ;; 14) rename_del_suffix ;; 15) rename_case_convert ;;
        16) rename_add_timestamp ;; 17) rename_random_all ;; 18) rename_single_folder ;;
        # 三、删除清理
        19) delete_empty_dir_recurse ;; 20) delete_empty_file_recurse ;;
        21) delete_dir_by_prefix ;; 22) delete_dir_by_suffix ;;
        23) delete_all_hidden_dir ;; 24) delete_all_num_dir ;;
        25) delete_all_random_dummy_dir ;; 26) delete_broken_link ;;
        27) recycle_restore ;; 28) recycle_clear ;; 29) file_shred ;;
        # 四、加密解密
        30) folder_encrypt_aes ;; 31) folder_decrypt_aes ;;
        32) batch_tar_compress ;; 33) batch_tar_decompress ;;
        34) file_md5_check ;; 35) file_sha1_check ;; 36) file_integrity_check ;;
        # 五、伪装
        37) disguise_sys_dir ;; 38) disguise_jpg ;; 39) disguise_mp4 ;;
        40) disguise_apk ;; 41) disguise_restore ;;
        # 六、权限
        42) set_perm_readonly ;; 43) set_perm_rw ;; 44) fix_perm_recurse ;;
        45) batch_set_readonly ;; 46) batch_set_rw ;;
        # 七、扫描统计
        47) dir_full_stat ;; 48) scan_dup_dir_name ;; 49) scan_dup_file ;;
        50) scan_big_file ;; 51) search_file_by_ext ;; 52) gen_dir_tree ;;
        53) export_dir_list ;; 54) stat_file_type_count ;; 55) sort_dir_by_size ;;
        # 八、复制移动备份
        56) copy_single_dir ;; 57) move_single_dir ;; 58) dir_full_backup ;;
        59) dir_restore_backup ;; 60) batch_copy_by_prefix ;;
        # 九、趣味
        61) dir_bomb_1000 ;; 62) dir_maze_random ;; 63) batch_create_empty_file ;;
        64) create_fixed_size_file ;; 65) file_simple_merge ;; 66) change_file_ext ;;
        # 十、系统工具
        67) show_storage_info ;; 68) show_sys_info ;; 69) change_pass ;;
        70) reset_pass ;; 71) view_log ;; 72) clear_log ;; 73) export_log ;;
        74) toggle_color ;; 75) toggle_loading ;; 76) toggle_log ;;
        77) show_help ;; 78) show_version ;;
        # 退出
        0) confirm "确认退出工具" && { pb "\n👋 感谢使用，再见"; exit 0; } ;;
        *) pr "❌ 无效序号，请重新输入" ;;
    esac
    printf "\n按回车键返回主菜单..."
    read -r tmp
done
