#!/bin/bash
#***************************************************************#
# ScriptName: cleanv2.0.sh
# Author: xhy
# Create Date: 2025-02-16 15:24
# Modify Date: 2025-02-16 15:24
# Version: v2
# Description: CentOS 7/8 Post-Installation Script (Optimized)
#***************************************************************#
set -euo pipefail
trap 'echo -e "\n\033[35m[ERROR] $BASH_COMMAND failed at line $LINENO\033[0m"; exit 1' ERR

# ------------------------------
# 全局配置区（需根据实际情况修改）
# ------------------------------
declare -A CONFIG=(
   # 功能开关
    [ENABLE_CLEAR]="yes"             # 是否清理垃圾
    [MACHINE_STATUS]="reboot"        # 机器状态，重启或者关机：reboot/shutdown
	[SHUTDOWN_DELAY]=1               # 关机/重启延迟时间（分钟）
)

# ------------------------------
# 环境系统版本检测
# ------------------------------
check_os_release() {
    echo -e "\n\n\033[33m[INFO] 检查当前系统版本...\033[0m"
    sleep 2

    # 系统平台检测
    if [[ -f /etc/redhat-release ]]; then
        PLATFORM=$(rpm -E %{rhel} 2>/dev/null || rpm -q --qf '%{VERSION}' -f /etc/redhat-release)
    else
        echo -e "\n\n\033[35m[ERROR] 仅支持 RedHat-based 系统...\033[0m"
        exit 1
    fi
	
    mkdir -p /var/log/sssd/
    echo -e "\n\033[32m[SUCC] 当前系统版本为：CentOS ${PLATFORM}...\033[0m"
    sleep 2
}

# ------------------------------
# 基础软件安装
# ------------------------------
install_base_tools() {
    echo -e "\n\n\033[33m[INFO] 安装基础常用软件...\033[0m"
    sleep 2
    
    local BASE_PKGS=(
        bash-completion bzip2 curl epel-release gcc gcc-c++ git htop
        jq libffi-devel lrzsz lsof lvm2 make net-tools openssh-clients
        openssl openssl-devel perl-IPC-Cmd perl-CPAN perl-interpreter perl-Pod-Html python3-pip screen tar
        tk-devel traceroute tree unzip vim wget xz yum-utils zlib zlib-devel
    )

    if (( PLATFORM == 8 )); then
        dnf -y install "${BASE_PKGS[@]}" chrony
        dnf -y update
    else
        yum -y install "${BASE_PKGS[@]}" ntp
        yum -y update
    fi
    echo -e "\n\033[32m[SUCC] 基础常用软件已安装完成...\033[0m"
    sleep 2
}

# ------------------------------
# 重启或关机
# ------------------------------
power_status() {
case "${CONFIG[MACHINE_STATUS]}" in
        reboot)
        echo -e "\n\n\033[34m[WARN] 操作系统将在1分钟后重启...\033[0m"
        shutdown -r +${CONFIG[SHUTDOWN_DELAY]}
            ;;
        shutdown)
        echo -e "\n\n\033[34m[WARN] 操作系统将在1分钟后关机...\033[0m"
        shutdown -h +${CONFIG[SHUTDOWN_DELAY]}
            ;;
        *) 
            echo -e "\n\n\033[34m[WARN] 清理完成不做任何处理...\033[0m"
            sleep 1

esac
    echo -e "\n\033[34m[WARN] 系统将在${CONFIG[SHUTDOWN_DELAY]}分钟后进行${CONFIG[MACHINE_STATUS]}处理...\033[0m"
    sleep 2
}

# ------------------------------
# 清理垃圾
# ------------------------------
clear_tmp() {
    if [[ "${CONFIG[ENABLE_CLEAR]}" == "yes" ]]; then
        echo -e "\n\n\033[33m[INFO] 开始清理所有残留...\033[0m"

        echo -e "\n\n\033[33m[INFO] 开始清理旧版本内核...\033[0m"

        # 获取当前运行内核的完整版本标识（如6.9.7-1.el7.elrepo.x86_64）
        CURRENT_KERNEL=$(uname -r)

        # 通过内核文件反向查询所属rpm包的完整名称（如kernel-ml-6.9.7-1.el7.elrepo.x86_64）
        CURRENT_PKG=$(rpm -qf "/boot/vmlinuz-${CURRENT_KERNEL}")

        # 提取核心版本号（如6.9.7-1.el7.elrepo）
        VERSION_RELEASE=$(rpm -q --queryformat '%{VERSION}-%{RELEASE}' "${CURRENT_PKG}")

        # 清理所有不包含当前版本标识的kernel相关包
        rpm -qa | grep '^kernel' | grep -vF "${VERSION_RELEASE}" | xargs -r yum -y remove || true
        
        echo -e "\n\n\033[32m[SUCCESS] 旧内核 kernel 已卸载完成...\033[0m"
        sleep 2
        
        echo -e "\n\n\033[33m[INFO] 开始清理所有历史日志...\033[0m"
        yum clean all 
        yum makecache

        LOGS_RMFILES=(
            /var/log/{anaconda/*,boot.log*,btmp*,chrony/*,cloud-init*,cron*,dmesg\.*,dnf*,grubby*,hawkey.log*,httpd/,kdump.log,ntpstats,messages*,openwebmail.log,qemu-ga*,rhsm*,samba*,secure*,sssd/*,tallylog,tuned/*,update*.log,vmware*,yum*}
            /var/spool/mail/root
)

        for rmlog in "${LOGS_RMFILES[@]}"; do
            rm -rf ${rmlog}
        done

        sleep 2

        LOGS_ECHOFILES=(
            /var/log/{audit/audit.log,boot.log,btmp,cron,dmesg,firewalld,syslog,lastlog,wtmp,maillog,messages,maillog,ntp.log,README,secure,spooler,sssd/sssd.log,tuned/tuned.log}
			${HOME}/.bash_history
)
        for echolog in "${LOGS_ECHOFILES[@]}"; do
            echo "" > ${echolog}
        done

        rm -rf /etc/yum.repos.d/epel.repo
        rm -rf /etc/yum.repos.d/epel-*.repo
        rm -rf /var/spool/mail/root
        
        rm -rf /tmp/*
		rm -rf /root/*
        
        history -c
        history -w
    fi  
    echo -e "\n\033[32m[SUCC] 系统日志已清理完成...\033[0m"
    sleep 2
}

# ------------------------------
# 主执行流程
# ------------------------------
main() {
    check_os_release
	install_base_tools
    clear_tmp
    power_status
}

main "$@"
