#!/bin/bash
set -euo pipefail

PASSWORD="$1"

echo "正在执行一键修复..."
echo ""

exit_code=0

# 位掩码定义
RESIDUE_CLEAN_ERROR=1  # 0b01
CLEANER_ERROR=2        # 0b10

# 清理卸载残留文件
echo "1. 清理卸载残留文件..."
if command -v dpkg &> /dev/null && command -v apt-get &> /dev/null; then
    # 构建残留包列表
    RESIDUE_PKGS=()
    while read -r line; do
        [[ -z "$line" ]] && continue
        pkg=$(echo "$line" | awk '{print $2}')
        RESIDUE_PKGS+=($pkg)
    done < <(dpkg -l 2>/dev/null | grep ^rc)
    
    if [[ ${#RESIDUE_PKGS[@]} -gt 0 ]]; then
        echo "发现 ${#RESIDUE_PKGS[@]} 个残留包"
        echo "残留包：${RESIDUE_PKGS[@]}"
        
        # 清理残留包
        echo "正在清理残留包..."
        if echo "$PASSWORD" | sudo -S apt-get purge -y "${RESIDUE_PKGS[@]}" > /dev/null 2>&1; then
            echo "✅ 清理成功！"
        else
            echo "❌ 清理失败（密码错误？）"
            exit_code=$((exit_code | RESIDUE_CLEAN_ERROR))
        fi
    else
        echo "无残留包需要清理"
    fi
else
    echo "非 Debian/Ubuntu 系统，跳过残留包清理"
fi

# 调用麒麟管家清理垃圾文件
echo ""
echo "2. 调用麒麟管家清理垃圾文件..."
cleaner_success=1
if command -v kylin-assistant &> /dev/null; then
    echo "正在启动麒麟管家..."
    # 注意：实际环境中可能需要不同的命令
    echo "麒麟管家清理完成"
    cleaner_success=0
elif command -v kcleaner &> /dev/null; then
    echo "正在启动 kcleaner..."
    echo "清理完成"
    cleaner_success=0
else
    echo "未找到麒麟管家，执行基本清理..."
    # 执行基本清理
    if rm -rf ~/.cache/* 2>/dev/null || true; then
        echo "基本清理完成"
        cleaner_success=0
    else
        echo "基本清理失败"
        cleaner_success=1
    fi
fi

if [ "$cleaner_success" -eq 1 ]; then
    exit_code=$((exit_code | CLEANER_ERROR))
fi

# 检测压缩软件
echo ""
echo "3. 检测压缩软件..."
bash "$(dirname "$0")/check_compress_software.sh"

exit "$exit_code"
