#!/usr/bin/env python

"""
Copyright (c) 2006-2024 sqlmap developers (https://sqlmap.org/)
See the file 'LICENSE' for copying permission
"""

# 导入所需的标准库和自定义模块
import functools  # 用于高阶函数和操作
import os        # 提供与操作系统交互的功能
import random    # 用于生成随机数
import shutil    # 提供高级文件操作
import stat      # 提供文件属性相关常量
import string    # 提供字符串常量

# 导入自定义工具函数
from lib.core.common import getSafeExString  # 安全地获取异常字符串
from lib.core.common import openFile         # 安全地打开文件
from lib.core.compat import xrange           # 兼容Python2/3的range函数
from lib.core.convert import getUnicode      # 转换为Unicode字符串
from lib.core.data import logger             # 日志记录器
from thirdparty.six import unichr as _unichr # 兼容Python2/3的unichr函数

def purge(directory):
    """
    安全地删除指定目录的所有内容
    参数:
        directory: 要清理的目录路径
    """

    # 检查目录是否存在
    if not os.path.isdir(directory):
        warnMsg = "skipping purging of directory '%s' as it does not exist" % directory
        logger.warning(warnMsg)
        return

    # 输出开始清理的信息
    infoMsg = "purging content of directory '%s'..." % directory
    logger.info(infoMsg)

    # 初始化存储文件路径和目录路径的列表
    filepaths = []
    dirpaths = []

    # 遍历目录树,收集所有文件和目录的绝对路径
    for rootpath, directories, filenames in os.walk(directory):
        dirpaths.extend(os.path.abspath(os.path.join(rootpath, _)) for _ in directories)
        filepaths.extend(os.path.abspath(os.path.join(rootpath, _)) for _ in filenames)

    # 第一步：修改所有文件的权限为可读可写
    logger.debug("changing file attributes")
    for filepath in filepaths:
        try:
            os.chmod(filepath, stat.S_IREAD | stat.S_IWRITE)
        except:
            pass

    # 第二步：用随机数据覆盖文件内容
    logger.debug("writing random data to files")
    for filepath in filepaths:
        try:
            filesize = os.path.getsize(filepath)
            with openFile(filepath, "w+b") as f:
                f.write("".join(_unichr(random.randint(0, 255)) for _ in xrange(filesize)))
        except:
            pass

    # 第三步：清空所有文件
    logger.debug("truncating files")
    for filepath in filepaths:
        try:
            with open(filepath, 'w') as f:
                pass
        except:
            pass

    # 第四步：将文件名替换为随机字母组合
    logger.debug("renaming filenames to random values")
    for filepath in filepaths:
        try:
            os.rename(filepath, os.path.join(os.path.dirname(filepath), "".join(random.sample(string.ascii_letters, random.randint(4, 8)))))
        except:
            pass

    # 按目录深度排序,确保先处理最深的目录
    dirpaths.sort(key=functools.cmp_to_key(lambda x, y: y.count(os.path.sep) - x.count(os.path.sep)))

    # 第五步：将目录名替换为随机字母组合
    logger.debug("renaming directory names to random values")
    for dirpath in dirpaths:
        try:
            os.rename(dirpath, os.path.join(os.path.dirname(dirpath), "".join(random.sample(string.ascii_letters, random.randint(4, 8)))))
        except:
            pass

    # 最后一步：删除整个目录树
    logger.debug("deleting the whole directory tree")
    try:
        shutil.rmtree(directory)
    except OSError as ex:
        logger.error("problem occurred while removing directory '%s' ('%s')" % (getUnicode(directory), getSafeExString(ex)))
