#!/bin/bash
set -euo pipefail

if [ "$1" == "execute" ]; then
    # 执行模式：杀死高压力进程
    echo "正在终止高压力进程..."
    
    # 查找资源占用最高的进程（排除系统进程）
    high_processes=$(ps aux --sort=-%cpu | grep -v "^root" | grep -v "^system" | grep -v "ps aux" | head -5)
    
    if [ -z "$high_processes" ]; then
        echo "未发现高压力进程"
        exit 0
    fi
    
    echo "发现以下高压力进程："
    echo "$high_processes"
    echo ""
    
    # 杀死这些进程
    echo "正在终止进程..."
    echo "$high_processes" | awk '{print $2}' | xargs -r kill -9 2>/dev/null || true
    
    echo ""
    echo "进程已全部终止！还有以下问题可修复："
    echo "1. 磁盘空间不足"
    echo "2. 系统缓存占用过大"
    echo "3. 卸载残留文件"
    echo "是否一键修复？[是/否]"
    
else
    # 检测模式：只检测不执行
    high_processes=$(ps aux --sort=-%cpu | grep -v "^root" | grep -v "^system" | grep -v "ps aux" | head -3)
    
    if [ -n "$high_processes" ]; then
        echo "诊断完成，发现高压力进程（紧急），建议优先处理[是/否]"
    else
        echo "诊断完成，未发现高压力进程"
    fi
fi
