#!/bin/bash 
# 自定义名称
PACKAGE_NAME="xiaoq-tools"
# 颜色定义 
RED='\033[0;31m' 
GREEN='\033[0;32m' 
YELLOW='\033[0;33m'
BLUE='\033[0;34m' 
NC='\033[0m' # No Color 
# 桌面通知函数 
notify() { 
    local title="$1" 
    local message="$2" 
    local level="$3" 
    local icon="${4:-}"  # 可选参数：图标路径
    case "$level" in 
        "success") 
            color="$GREEN" 
            urgency="normal" 
            ;; 
        "warning") 
            color="$BLUE" 
            urgency="normal" 
            ;; 
         "wrong") 
            color="$YELLOW" 
            urgency="normal" 
            ;;              
        "error") 
            color="$RED" 
            urgency="critical" 
            ;; 
        *) 
            color="$NC" 
            urgency="normal" 
            ;; 
    esac 
    echo -e "${color}${message}${NC}" 
    # 带图标和不带图标的两种调用方式
    if [[ -n "$icon" ]]; then
        notify-send -u "$urgency" -i "$icon" "$title" "$message" 2>/dev/null || true
    else
        notify-send -u "$urgency" "$title" "$message" 2>/dev/null || true
    fi
} 
#=====# 优化图标路径检查==========
ICON_PATH="/usr/share/icons/xiaoq-file-cleaner.png"
[[ ! -f "$ICON_PATH" ]] && ICON_PATH=""  # 图标不存在时不显示

# ====================== 版本检查 ======================
GITEE_REPO="https://gitee.com/seeker_ok/${PACKAGE_NAME}"
LOCAL_VERSION=$(dpkg-query -W --showformat='${Version}' ${PACKAGE_NAME} 2>/dev/null)

# 获取远程版本号，设置3秒超时
REMOTE_CONTROL=$(curl -sL --connect-timeout 3 --max-time 3 "${GITEE_REPO}/raw/master/DEBIAN/control")

# 检查curl是否成功获取内容
if [ -z "$REMOTE_CONTROL" ]; then
  echo -e "${blue}无法在3秒内连接到远程服务器，跳过版本检查${nc}"
else
  remote_version=$(echo "$REMOTE_CONTROL" | grep 'Version:' | awk '{print $2}')
  
  # 版本比较函数
  version_compare() {
    if [ "$1" = "$2" ]; then
      return 0
    fi
    local IFS=.
    local i ver1=($1) ver2=($2)
    for ((i=${#ver1[@]}; i<${#ver2[@]}; i++)); do
      ver1[i]=0
    done
    for ((i=0; i<${#ver1[@]}; i++)); do
      if [[ -z ${ver2[i]} ]]; then
        ver2[i]=0
      fi
      if ((10#${ver1[i]} > 10#${ver2[i]})); then
        return 1
      fi
      if ((10#${ver1[i]} < 10#${ver2[i]})); then
        return 2
      fi
    done
    return 0
  }

  if version_compare "$LOCAL_VERSION" "$remote_version"; then
    : # 本地版本与远程版本相同，不执行任何操作
  elif [ $? -eq 1 ]; then
    echo -e "${red}本地版本 ${LOCAL_VERSION} 比远程版本 ${remote_version} 新${nc}"
  else
    echo -e "${green}发现${PACKAGE_NAME}有新版本 ${remote_version}，是否更新？[Yy/N]${nc}"
    read -p " " choice
    if [[ "$choice" = "y" || "$choice" = "Y" ]]; then
      deb_url="${GITEE_REPO}/raw/master/${PACKAGE_NAME}_${remote_version}_all.deb"
      x-terminal-emulator -e "bash -c \"
        export DISPLAY='$DISPLAY' XAUTHORITY='$XAUTHORITY';  # 传递环境变量
        echo -e '${green}正在下载并安装新版本,请稍等...${nc}';
        wget -q ${deb_url} -O /tmp/${PACKAGE_NAME}.deb && 
        sudo apt install -y /tmp/${PACKAGE_NAME}.deb && 
        rm -rf /tmp/${PACKAGE_NAME}.deb;
        echo -e '${green}软件已更新至 ${remote_version}，请关闭窗口重新运行${nc}';
        read -p $'${blue} 按任意键关闭此窗口...${nc}' \""
      exit 1
    fi
  fi
fi
#=====【检测软件是否有新的版本结束】==========

# 免责声明
notify "软件使用免责声明" "免责声明:本软件具备【强制删除】文件及文件夹功能，可能造成不可逆数据损失。请在使用前仔细阅读以下条款，确认理解所有操作风险后方可继续使用。您的使用行为将视为对本协议全部条款的认可与接受。\n1.1 、使用本软件前，用户应自行对重要文件进行备份;\n1.2、本软件为免费开源程序，不提供任何形式的技术支持;\n1.3、因用户操作失误、未阅读提示、擅自修改程序等行为导致的数据损失，开发者不承担任何法律责任;\n1.4、使用本软件进行非法操作产生的后果由用户自行承担" "error"  "$ICON_PATH"
echo -ne "\e]2;小Q一键强制删除\a"
# 检查是否是系统关键文件 
is_critical_file() { 
    local filepath=$1 
    # 定义系统关键目录和文件列表 
    local critical_paths=( 
        "/bin" "/sbin" "/usr/bin" "/usr/sbin" "/lib" "/usr/lib" "/lib64" "/usr/lib64" 
        "/etc" "/var" "/boot" "/root" "/dev" "/proc" "/sys" "/run" 
        "/usr/local/bin" "/usr/local/sbin"  "/home"   "/proc"   "/srv"   "/backup"
    ) 
    # 检查是否是系统关键文件 
    for path in "${critical_paths[@]}"; do 
        if [[ "$filepath" == "$path"* ]]; then 
            return 0 # 是系统关键文件 
        fi 
    done 
    return 1 # 不是系统关键文件 
} 
# 解除防止编辑权限（递归处理目录及其下所有文件） 
remove_immutable_flags() { 
    local target=$1 
    # 检查文件/目录是否存在 
    if [ ! -e "$target" ]; then 
        echo "路径错误-目标不存在: $target" "error"
        return 1 
    fi 
    # 处理单个文件 
    if [ -f "$target" ] || [ -L "$target" ]; then 
        if lsattr "$target" 2>/dev/null | grep -q "i"; then 
            if ! sudo chattr -i "$target"; then 
                echo "权限错误-无法移除文件的不可变标志"  "error"
                return 1 
            fi 
            echo "权限更新-已移除不可变标志: $target"  "success" 
        fi 
        return 0 
    fi 
    # 处理目录（递归） 
    if [ -d "$target" ]; then 
        # 处理目录本身 
        if lsattr -d "$target" 2>/dev/null | grep -q "i"; then 
            if ! sudo chattr -i "$target"; then 
                echo "权限错误:无法移除目录的不可变标志"
                return 1 
            fi 
            echo "权限更新:已移除目录不可变标志: $target"
        fi 
        # 递归处理目录内容 
        local success=true 
        while IFS= read -r -d $'\0' item; do 
            if lsattr "$item" 2>/dev/null | grep -q "i"; then 
                if ! sudo chattr -i -R "$item"; then 
                    echo "权限错误-无法移除项目的不可变标志: $item"    "error"
                    success=false 
                else 
                    echo "权限更新-已移除不可变标志: $item"
                fi 
            fi 
        done < <(sudo find "$target" -exec printf '%s\0' {} + 2>/dev/null) 
        $success && return 0 || return 1 
    fi 
    return 0 
} 
# 主函数 
main() { 
 # 保存原始参数 
ORIGINAL_ARGS=("$@") 
# 提前获取sudo权限 
if [ $(id -u) -ne 0 ]; then 
    sudo -v || { notify "错误" "需要sudo权限" "error"; exit 1; } 
    # 重新设置参数，因为sudo可能会重置它们 
    set -- "${ORIGINAL_ARGS[@]}" 
fi 
# 检查是否提供了路径参数 
if [ $# -eq 0 ]; then 
     echo -e "\n\033[34m 提示:请拖放文件/文件夹到此处或直接输入路径\033[0m"
     read -p ": " target_path 
else 
    # 处理可能包含引号的路径 
        target_path=$(printf "%s" "$*" | sed "s/'//g; s/\"//g") 
fi 
# 处理路径格式（兼容统信UOS和麒麟系统） 
process_path() { 
    local target_path="$1" 
    # 处理file://协议路径 
    if [[ "$target_path" == file://* ]]; then 
        target_path="${target_path#file://}" 
        target_path=$(echo "$target_path" | sed 's/%20/ /g') # 解码URL编码 
    fi 
    # 处理麒麟系统可能的多重引号问题 
    target_path=$(echo "$target_path" | sed "s/^'\+//;s/'\+$//;s/^\"\+//;s/\"\+$//") 
    echo "$target_path" 
} 
target_path=$(process_path "$target_path") 
# 验证路径是否存在 
if [ ! -e "$target_path" ]; then 
    notify "错误" "路径无效（请重新确认路径，而不能为空）: $target_path" "error"    "$ICON_PATH"
    exit 1 
fi 
    # 检查是否是系统关键文件 
    if is_critical_file "$target_path"; then 
        echo -e "\033[33m警告：您正在尝试删除系统关键文件或目录！\033[0m" 
        read -p "这可能导致系统不稳定或无法启动！确定要继续吗？(Yy/n): " confirm 
        confirm=$(echo "$confirm" | tr '[:upper:]' '[:lower:]')  # 转换为小写 
        if [ "$confirm" != "y" ]; then 
            echo -e "\n\033[34m 操作取消:用户取消删除系统关键文件\033[0m"
            exit 1 
        fi 
    fi 
    # 二次确认 
    echo "您输入的路径是: $target_path" 
    read -p "请再次确认路径是否正确 (Yy/n): " confirm 
    confirm=$(echo "$confirm" | tr '[:upper:]' '[:lower:]')  # 转换为小写 
    if [ "$confirm" != "y" ]; then 
        echo -e "\n\033[34m 操作取消:用户取消删除系统关键文件\033[0m"
        exit 1 
    fi 
    # 询问是否解除防止编辑权限 
    echo -e "\033[34m注意：解除防止编辑权限可能会改变系统的安全设置，请谨慎操作。\033[0m" 
    read -p "是否要解除目录及子目录下所有文件的防止编辑权限？(Yy/n): " remove_immutable 
    remove_immutable=$(echo "$remove_immutable" | tr '[:upper:]' '[:lower:]')  # 转换为小写 

# 修改 remove_immutable_flags 函数的返回值处理逻辑
if [ "$remove_immutable" = "y" ]; then 
    # 处理符号链接的返回码
    remove_immutable_flags "$target_path"
    local result=$?
    # 结果处理优化：仅当严重错误时才退出
    if [ $result -eq 1 ]; then
        echo -e "\n${YELLOW}警告：部分文件的不可变标志无法解除${NC}"
        read -p "是否继续删除操作？(Yy/n): " continue_choice
        continue_choice=$(echo "$continue_choice" | tr '[:upper:]' '[:lower:]')
        if [ "$continue_choice" != "y" ]; then
            echo -e "\n${BLUE}操作取消:用户取消删除${NC}"
            exit 1
        fi
    elif [ $result -eq 2 ]; then
        # 符号链接无法解除标志，直接尝试删除
        echo -e "\n${YELLOW}尝试直接删除受保护的符号链接...${NC}"
    fi
    echo "权限更新-已完成防止编辑权限解除（部分文件可能仍受保护）" "warning"
fi
# 处理单个文件或符号链接 
    if [ -f "$target_path" ] || [ -L "$target_path" ]; then 
        # 权限处理 
        if ! sudo chmod u+w "$target_path"; then 
            echo  "权限错误-无法修改文件/链接权限"  "error" 
            exit 1 
        fi 
        notify "权限更新" "已设置文件/链接可写权限" "success"   "$ICON_PATH"
        # 删除文件或链接 
        if sudo rm -fv "$target_path"; then 
            echo "已成功删除: $target_path"
        else 
            notify  "操作异常" "删除过程中出现错误"  "error"   "$ICON_PATH"
            exit 1 
        fi 
        exit 0 
    fi 
    if [ -L "$target_path" ]; then 
        # 直接删除符号链接（不执行 chmod）
        if sudo rm -fv  $(echo "$target_path" | sed "s/^/\"/;s/$/\"/"); then 
            echo "已成功删除符号链接: $target_path"
        else 
            echo   "操作异常-符号链接删除过程中出现错误"  "error"
            exit 1 
        fi 
        exit 0
    fi
# 目录处理逻辑 
    if ! sudo chmod -R u+w "$target_path"; then 
        echo "权限错误:无法修改目录权限"
        exit 1 
    fi 
       echo "权限更新:已设置目录可写权限"
# 单独处理符号链接 
    if sudo find "$target_path" -type l -exec rm -fv {} +; then 
        echo "清理完成:已删除目录中的所有符号链接"
    else 
        echo  "操作异常-符号链接删除过程中出现错误" "error" 
    fi 
# 文件类型处理 
    read -p "请输入要保留的文件类型（多个用逗号分隔，留空删除所有）: " file_extension 
    if [ -n "$file_extension" ]; then 
        IFS=',' read -ra exts <<< "$file_extension" 
        local find_args=() 
        for ext in "${exts[@]}"; do 
            ext=$(echo "$ext" | xargs) 
            [ -z "$ext" ] && continue 
            [[ "$ext" != *\** ]] && ext="*.$ext" 
            find_args+=("-name" "$ext") 
        done 

        if [ ${#find_args[@]} -eq 0 ]; then 
            notify "操作取消" "无效的文件类型参数" "error"  "$ICON_PATH"
            exit 1 
        fi 
# 构建查找条件 
        local condition=("!" "(") 
        for ((i=0; i<${#find_args[@]}; i+=2)); do 
            [ $i -gt 0 ] && condition+=("-o") 
            condition+=("${find_args[$i]}" "${find_args[$i+1]}") 
        done 
        condition+=(")") 
# 执行保留删除 
        if sudo find "$target_path" -type f "${condition[@]}" -exec rm -fv {} +; then 
            echo  "清理完成:已完成选择性文件删除"
        else 
            notify "操作异常" "文件删除过程中出现错误" "error"  "$ICON_PATH"
        fi 
    else 
# 全量删除 
        if sudo find "$target_path" -type f -exec rm -fv {} +; then 
            notify "清理完成" "已删除所有文件" "success"  "$ICON_PATH"
        else 
            echo   "操作异常-全量删除过程中出现错误"  "error"
        fi 
    fi 
# 清理空目录 
    sudo find "$target_path" -mindepth 1 -type d -empty -delete 2>/dev/null 
    if [ -d "$target_path" ] && [ -z "$(ls -A "$target_path")" ]; then 
        if sudo rmdir "$target_path"; then 
            echo  "清理完成:已移除空目录: $target_path"
        fi 
    fi 
    notify  "操作完成" "文件清理流程已成功结束"  "success"  "$ICON_PATH"
} 
# 执行主函数 
main "$@" 
echo  "感谢您使用本软件，软件免费使用与更新，具体软件更新请访问以下网址：https://gitee.com/seeker_ok/xiaoq-tools"
read -p "按回车键退出..." 
exit 0 