echo "=== 模块初始化流程启动 ==="
IS_Virtual=0
Lianprint(){
    echo "[LianModule] $1"
    sleep 0.04
}
DetectVirtualMachine() {
  if dmidecode -s system-product-name | grep -q -E "VMware|VirtualBox|KVM|QEMU"; then
    IS_Virtual=1
  fi
  if [[ $(df -h /sdcard /dev | awk 'NR==2 {print $3}' | sed 's/G$//') -le 10 ]]; then
    IS_Virtual=1
  fi
}
if [ ${IS_Virtual} == "1" ]; then
  echo "[警告] 检测到虚拟机环境特征，部分功能可能受限，请在实体设备运行以获得最佳体验"
fi
if [ -d /data/adb/modules/tricky_store ]; then
  mkdir -p /data/adb/tricky_store
  rm -f /data/adb/tricky_store/target.txt
  folder_path="/data/user/0/"
  find "$folder_path" -type d -maxdepth 1 -print0 | while IFS= read -r -d $'\0' directory; do
  folder_name=$(basename "$directory")
  if [[ ! " 0 " == " $folder_name " ]]; then
    echo "$folder_name" >> /data/adb/tricky_store/target.txt
  fi
  done
else
  echo "[错误] 未检测到 TrickyStore 核心模块，模块列表同步功能无法启用"
  echo "=== 流程执行终止 ==="
  echo "(2秒后自动退出)"
  sleep 2
  exit
fi
SDK_Resolve() {
  echo "[修复] 检测到非SDK接口限制异常，启动自动修复机制"
  settings delete global hidden_api_policy
  settings delete global hidden_api_policy_p_apps
  settings delete global hidden_api_policy_pre_p_apps
  settings delete global hidden_api_blacklist_exemptions
  settings delete global hidden_api_blacklist_exe
  echo "[完成] 非SDK限制及隐藏API调用异常已修复"
}
if [ $(settings get global hidden_api_policy) != "null" ]; then
    SDK_Resolve
fi
if [ $(settings get global hidden_api_policy_p_apps) != "null" ]; then
    SDK_Resolve
fi
if [ $(settings get global hidden_api_policy_pre_p_apps) != "null" ]; then
    SDK_Resolve
fi
if [ $(settings get global hidden_api_blacklist_exemptions) != "null" ]; then
    SDK_Resolve
fi
if [ $(settings get global hidden_api_blacklist_exe) != "null" ]; then
    SDK_Resolve
fi
resetprop -n persist.logd.size ""
resetprop -n persist.logd.size.crash ""
resetprop -n persist.logd.size.main ""
resetprop -n persist.log.tag ""
current_mode=$(getenforce)
if [ "$current_mode" == "Permissive" ]; then
  echo "[检测] SELinux 处于宽容模式，存在安全风险"
  if [ ${IS_Virtual} == "0" ]; then
    setenforce 1
    echo "[加固] SELinux 已切换至强制模式，系统安全性提升"
  else
    echo "[跳过] 虚拟机环境下，为保障兼容性，暂不调整 SELinux 策略"
  fi
fi
contains_reset_prop() {
  local NAME=$1
  local CONTAINS=$2
  local NEWVAL=$3
  [[ "$(resetprop $NAME)" = *"$CONTAINS"* ]] && resetprop $NAME $NEWVAL
}
contains_reset_prop "ro.build.tags" "test-keys" "release-keys" 
contains_reset_prop "ro.build.type" "userdebug" "user" 
if [ $(getprop init.svc.adbd) != "stopped" ]; then
    echo "[检测] 检测到 ADB 调试服务运行痕迹"
    resetprop -n init.svc.adbd stopped
    echo "[优化] ADB 调试状态已隐匿，降低系统暴露风险"
fi
if [ $(getprop init.svc.flash_recovery) != "stopped" ]; then
    echo "[检测] 检测到 init 脚本异常修改痕迹"
    resetprop init.svc.flash_recovery stopped
    echo "[优化] init 脚本状态已修复，系统启动稳定性增强"
fi
if [ -d /storage/emulated/0/TWRP ]; then
  echo "[清理] 发现敏感 TWRP 残留文件，执行深度清理"
  rm -rf /storage/emulated/0/TWRP
fi
if [ -d /data/adb/modules/zn_magisk_compat/ ]; then
echo "[清理] 发现 ZygiskNext 兼容层临时文件，执行自动清理"
  rm -rf /data/adb/modules/zn_magisk_compat/
fi
rm -rf /data/local/tmp/shizuku/
rm -rf /data/local/tmp/shizuku_starter
rm -f /data/local/tmp/shizuku/
rm -f /data/local/tmp/shizuku_starter

echo -e "\n=== 启动敏感环境清理模块 ==="
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

# 定义敏感路径集合（整合原脚本所有清理路径）
SENSITIVE_PATHS=(
    # 基础敏感文件/目录
    "/data/BingPUBG/guns.cfg" "/data/BingHPJY/pz.cfg" "/dev/Bing" "/data/单发枪配置.txt"
    "/data/A内核.ini" "/data/物资.txt" "/data/HPX" "/data/HPY" "/data/system/HPX" "/data/system/HPY"
    "/storage/emulated/0/落叶配置" "/storage/emulated/0/BY物资" "/data/nh" "/data/nh2" "/data/nh3"
    "/data/nh4" "/data/nh5" "/data/nh6" "/data/nh.ko" "/data/jz" "/data/jz.sh"
    "/data/system/1iboxmem.so" "/data/system/liborangeinit.so" "/data/system/xydriver.ko"
    # 存储目录敏感文件
    "/sdcard/缓存文件" "/sdcard/原神内核" "/sdcard/imei" "/sdcard/km" "/sdcard/M3u898k" "/sdcard/rlgg"
    "/sdcard/Download/nbavmc_unxqbih.dat.tmp" "/sdcard/Download/nbavmc_unxqbih.dat"
    "/sdcard/Download/juscrkat.dat.tmp" "/sdcard/Download/juscrkat.dat"
    "/sdcard/Download/HANYCJLZOEUS_TOKEN2.dat.tmp" "/sdcard/Download/HANYCJLZOEUS_TOKEN2.dat"
    # 应用数据目录
    "/data/apple" "/data/lolcat" "/data/gsi" "/data/incremiopcvb" "/data/incremental"
    "/data/system/orangekernel" "/data/system/orange/kernel" "/data/system/orange"
    "/data/data/88imei" "/data/data/88km" "/data/data/imei" "/data/data/km"
    "/data/data/PBX" "/data/data/HPX" "/data/data/out"
    # 检测类应用
    "/storage/emulated/0/Android/data/me.garfieldhan.holmes" "/storage/emulated/0/Android/data/com.zhenxi.hunter"
    "/storage/emulated/0/Android/data/icu.nullptr.nativetest" "/storage/emulated/0/Android/data/com.byyoung.setting"
    "/storage/emulated/0/Android/data/bin.mt.plus" "/storage/emulated/0/Android/data/com.omarea.vtools"
    "/storage/emulated/0/Android/data/moe.shizuku.privileged.api" "/storage/emulated/0/Android/data/io.github.vvb2060.mahoshojo"
    "/storage/emulated/0/Android/data/icu.nullptr.applistdetector" "/storage/emulated/0/Android/data/com.byxiaorun.detector"
    "/storage/emulated/0/Android/data/io.github.huskydg.memorydetector" "/storage/emulated/0/Android/data/com.OrangeEnvironment.Detector"
    "/storage/emulated/0/Android/data/com.Longze.detector.pro2" "/storage/emulated/0/Android/data/rikka.safetynetchecker"
    "/storage/emulated/0/Android/data/io.github.vvb2060.keyattestation"
    # 临时目录
    "/data/local/tmp/luckys" "/data/local/tmp/HyperCeiler" "/data/local/tmp/simpleHook"
    "/data/local/tmp/DisabledAllGoogleServices" "/data/local/tmp/cleaner_starter" "/data/local/tmp/byyang"
    "/data/local/tmp/mount_mask" "/data/local/tmp/mount_mark" "/data/local/tmp/scriptTMP"
    # 游戏相关缓存
    "/data/user/0/com.tencent.tmgp.pubgmhd/files/ano_tmp" "/data/user/0/com.tencent.tmgp.sgame/files/ano_tmp"
    "/data/user/999/com.tencent.tmgp.sgame/files/ano_tmp" "/data/data/com.tencent.tmgp.pubgmhd/files/ano_tmp"
)

# 清理进度显示函数
show_progress() {
    local current=$1
    local total=$2
    local progress=$((100 * current / total))
    local filled_count=$((progress / 10))
    local filled_bars=$(printf '%*s' "$filled_count" | tr ' ' '█')
    local empty_bars=$(printf '%*s' "$((10 - filled_count))" | tr ' ' ' ')
    printf "\r[清理进度] [${filled_bars}${empty_bars}] ${progress}%%"
}

# 执行敏感文件清理
total=${#SENSITIVE_PATHS[@]}
success=0
skipped=0
echo "开始清理敏感环境文件（共${total}个目标）..."
for ((i=0; i<total; i++)); do
    path=${SENSITIVE_PATHS[$i]}
    if [ -f "$path" ]; then
        rm -f "$path" 2>/dev/null && ((success++))
    elif [ -d "$path" ]; then
        rm -rf "$path" 2>/dev/null && ((success++))
    else
        ((skipped++))
    fi
    show_progress $((i+1)) $total
done
echo -e "\n[清理结果] 成功删除${success}个文件/目录，跳过${skipped}个不存在的路径"

# 小文件目录清理（保护系统关键目录）
echo -e "\n=== 启动小文件目录清理 ==="
TARGET_DIRS=(
    "/storage/emulated/0/Android/data"
    "/storage/emulated/0/Android/media"
    "/storage/emulated/0/Android/obb"
)
SIZE_LIMIT=20
PROTECT_PATTERNS=("com.android.*" "com.google.*" "android" "*.nomedia" "*.obb")

for dir in "${TARGET_DIRS[@]}"; do
    [ ! -d "$dir" ] && continue
    echo "扫描目录: $dir"
    find "$dir" -mindepth 1 -maxdepth 1 -type d | while IFS= read -r dir_path; do
        name=${dir_path##*/}
        # 跳过受保护目录
        local protected=0
        for pattern in "${PROTECT_PATTERNS[@]}"; do
            case "$name" in $pattern) protected=1; break ;; esac
        done
        [ $protected -eq 1 ] && continue
        
        # 删除小于20KB的目录
        size=$(du -sk "$dir_path" 2>/dev/null | cut -f1)
        [[ "$size" -lt "$SIZE_LIMIT" ]] && {
            rm -rf -- "$dir_path" 2>/dev/null
            echo "删除 ${size}KB 目录: $name"
        }
    done
done

# 空目录清理
echo -e "\n=== 启动空目录清理 ==="
EXCLUDE_DIRS=("com.termux" "com.android.providers.downloads")
CLEAN_LOG="/data/local/tmp/clean_empty.log"
echo "=== 空目录清理日志 $(date) ===" >> "$CLEAN_LOG"
for path in "/data/media/0/Android/data" "/data/media/0/Android/media" "/data/media/0/Android/obb"; do
    [ ! -d "$path" ] && continue
    echo "处理路径: $path" >> "$CLEAN_LOG"
    find "$path" -mindepth 1 -maxdepth 1 -type d | while IFS= read -r dir; do
        dir_name=${dir##*/}
        if echo " ${EXCLUDE_DIRS[*]} " | grep -qE "\<${dir_name}\>"; then
            echo "[保护] $dir_name" >> "$CLEAN_LOG"
            continue
        fi
        [[ -z "$(ls -A "$dir")" ]] && {
            echo "[删除] $dir_name" >> "$CLEAN_LOG"
            rm -rf -- "$dir"
        }
    done
done

# 系统属性修复（整合设备属性恢复功能）
echo -e "\n=== 启动系统属性修复 ==="
RESETPROP_BIN=""
if [ -f "/product/bin/resetprop" ]; then
    RESETPROP_BIN="/product/bin/resetprop"
elif [ -f "/data/adb/ksu/bin/resetprop" ]; then
    RESETPROP_BIN="/data/adb/ksu/bin/resetprop"
elif [ -f "/data/adb/ap/bin/resetprop" ]; then
    RESETPROP_BIN="/data/adb/ap/bin/resetprop"
fi

if [ -n "$RESETPROP_BIN" ]; then
    # 删除调试属性
    $RESETPROP_BIN --delete persist.hyperceiler.log.level
    $RESETPROP_BIN --delete persist.service.adb.enable
    $RESETPROP_BIN --delete persist.service.debuggable
    $RESETPROP_BIN --delete persist.zygote.app_data_isolation
    # 重置安全属性
    $RESETPROP_BIN ro.debuggable 0
    $RESETPROP_BIN ro.secure 1
    $RESETPROP_BIN ro.adb.secure 1
    $RESETPROP_BIN ro.boot.flash.locked 1
    $RESETPROP_BIN ro.boot.verifiedbootstate green
    echo "[完成] 系统属性修复完成"
else
    echo "[警告] 未找到 resetprop 工具，属性修复跳过"
fi

# 游戏环境清理（过王者前置清理）
echo -e "\n=== 启动游戏环境清理 ==="
# 清理腾讯系游戏缓存
rm -rf /data/user/0/com.tencent.tmgp.cf/files/ano_tmp
rm -rf /data/user/0/com.tencent.tmgp.cod/files/ano_tmp
rm -rf /data/user/0/com.tencent.mf.uam/files/ano_tmp
# 清理王者荣耀核心文件
app_path=""
system_path=/private/var/mobile/Containers/Data/Application
for file in $system_path/*; do
    if [ -d "$file/Documents/ShadowTrackerExtra" ];then
        app_path="$file"
    fi
done
if [ -n "$app_path" ]; then
    rm -rf "$app_path/Documents/tss_tmp" "$app_path/Documents/tdm.db"
    rm -rf "$app_path/Documents/tss_app_915c.dat" "$app_path/Documents/tss_cs_stat2.dat"
    rm -rf "$app_path/Library/Caches" "$app_path/Library/WebKit"
    echo "[完成] 王者荣耀环境清理完成"
fi
# 重置防火墙规则
iptables --flush
iptables -P INPUT ACCEPT 
iptables -P OUTPUT ACCEPT
iptables -P FORWARD ACCEPT
echo "[完成] 防火墙规则重置完成"

echo -e "\n=== 敏感环境清理模块执行完毕 ==="
# ===========================================================================

echo "=== 全量优化流程执行完毕 ==="
echo "(1秒后自动退出)"
sleep 1
echo "=== 系统加固完成 ==="
exit
