#!/bin/bash
# ----------------------------------------------------------------------
# Kernel v7.0.7 Compilation and Installation Script for OpenEuler 25.09
# Author: AutoClaw AI Agent (Optimized)
# Date: 2026-05-15
# Description: This script automates the download, configuration, compilation,
#              and installation of Linux Kernel v7.0.7 from source code on OpenEuler 25.09.
# IMPORTANT: Must be run as root or with sudo privileges.
# ----------------------------------------------------------------------

# Set strict mode for scripting (Exit immediately if a command exits with a non-zero status)
set -euo pipefail

KERNEL_VERSION="7.0.7"
SOURCE_URL="https://mirrors.tuna.tsinghua.edu.cn/kernel/v${KERNEL_VERSION}.tar.xz" # Use reliable mirror
TEMP_DIR="/tmp/kernel_build"
INSTALL_PATH="/boot/vmlinuz-${KERNEL_VERSION}"

echo -e "\n==========================================================="
echo "🚀 Kernel v${KERNEL_VERSION} Compilation & Installation Started 🚀"
echo "Target System: OpenEuler 25.09"
echo "===========================================================\n"


# =========================================
# STEP 1: Dependency Check and Installation
# =========================================
function check_dependencies() {
    echo "[STEP 1/6] Checking system dependencies..."

    # Core dependencies required for building Linux kernels
    DEPENDENCIES=(make gcc flex bison perl git bc build-essential kernel-devel)

    local missing_deps=0
    for dep in "${DEPENDENCIES[@]}"; do
        if ! dpkg -l | grep -q "^ii.*$dep"; then # Check if package is installed (using common tools like dnf/apt syntax check)
            echo "  [!] Warning: Dependency '$dep' might be missing."
            missing_deps=1
        fi
    done

    if [ $missing_deps -eq 1 ]; then
        echo "  [i] Attempting to install critical development tools. This may require root privileges..."
        # On OpenEuler, dnf or yum is typically used. We prioritize dnf/zypper for modern systems.
        if command -v dnf &> /dev/null; then
            sudo dnf groupinstall "Development Tools" -y > /dev/null 2>&1 || { echo "Error: Failed to install development groups via DNF."; return 1; }
            sudo dnf install "${DEPENDENCIES[@]}" -y > /dev/null 2>&1 || { echo "Error: One or more dependencies failed to install. Please check network and repositories."; return 1; }
        elif command -v yum &> /dev/null; then
             sudo yum groupinstall "Development Tools" -y > /dev/null 2>&1 || { echo "Error: Failed to install development groups via YUM."; return 1; }
             sudo yum install "${DEPENDENCIES[@]}" -y > /dev/null 2>&1 || { echo "Error: One or more dependencies failed to install. Please check network and repositories."; return 1; }
        else
            echo "Fatal Error: Neither DNF nor YUM package manager found. Cannot proceed."
            return 1
        fi
    else
        echo "  [+] All necessary development tools appear to be installed or the system is sufficiently configured."
    fi
    return 0
}


# =========================================
# STEP 2: Source Code Download and Preparation
# =========================================
function download_and_extract() {
    echo -e "\n[STEP 2/6] Downloading kernel source v${KERNEL_VERSION}..."

    # Ensure clean state before starting
    if [ -d "$TEMP_DIR" ]; then
        echo "  [i] Cleaning up previous build directory: $TEMP_DIR"
        rm -rf "$TEMP_DIR"
    fi
    mkdir -p "$TEMP_DIR" || { echo "Error: Failed to create temporary directory $TEMP_DIR."; return 1; }

    # Download the source tarball
    echo "  [i] Downloading from: $SOURCE_URL"
    wget -q --show-progress "$SOURCE_URL" -O /tmp/linux-${KERNEL_VERSION}.tar.xz || { echo "Fatal Error: Failed to download kernel source from '$SOURCE_URL'. Check internet connection or URL."; return 1; }

    # Extract the source code into the temporary directory
    echo "  [i] Extracting source code..."
    tar -xf /tmp/linux-${KERNEL_VERSION}.tar.xz -C "$TEMP_DIR" --strip-components=1 || { echo "Fatal Error: Failed to extract kernel source."; return 1; }

    # Cleanup download file
    rm /tmp/linux-${KERNEL_VERSION}.tar.xz
    echo "[+] Kernel source code successfully extracted into $TEMP_DIR."
}


# =========================================
# STEP 3: Configuration
# =========================================
function configure_kernel() {
    echo -e "\n[STEP 3/6] Running kernel configuration..."

    cd "$TEMP_DIR" || { echo "Fatal Error: Cannot change directory to $TEMP_DIR."; return 1; }

    # 1. Clean up old build artifacts (essential for clean compile)
    make mrproper || { echo "Warning: make mrproper failed, but continuing..."; }

    # 2. Set a base configuration (defconfig is the simplest starting point)
    echo "  [i] Generating default configuration using 'defconfig'..."
    make defconfig || { echo "Fatal Error: Failed to run make defconfig. Check kernel version compatibility."; return 1; }

    # Optional but recommended: Use 'menuconfig' for customized features (requires utility)
    echo "  [i] Configuration completed. Review the generated .config file inside $TEMP_DIR."
}


# =========================================
# STEP 4: Compilation
# =========================================
function compile_kernel() {
    local cores=$(nproc)
    echo -e "\n[STEP 4/6] Compiling kernel using maximum available processors ($cores)..."

    # Compile the core kernel image and modules (using all cores for speed)
    make -j"$cores" || { echo "Fatal Error: Kernel compilation failed. Check compile logs above."; return 1; }

    echo "[+] Compilation successful! Kernel images are built."
}


# =========================================
# STEP 5: Installation
# =========================================
function install_kernel() {
    echo -e "\n[STEP 5/6] Installing kernel modules and images to the system..."

    cd "$TEMP_DIR" || return 1

    # 1. Install modules (builds /lib/modules/<version>)
    echo "  [i] Running make modules_install..."
    make modules_install || { echo "Error: Module installation failed."; return 1; }

    # 2. Install the kernel image and headers
    echo "  [i] Running make install (installs vmlinuz, System.map, etc.)."
    sudo make install || { echo "Error: Kernel image installation failed. Check permissions or required system paths."; return 1; }

    echo "[+] Installation successful! New kernel version is active in /boot."
}


# =========================================
# STEP 6: Cleanup and Reboot Instructions
# =========================================
function cleanup_and_reboot() {
    echo -e "\n==========================================================="
    echo "✨ Kernel Compilation Process Complete! ✨"
    echo "==========================================================="

    echo ""
    echo "✅ 成功完成所有编译和安装步骤。"
    echo "请注意以下几点："
    echo "1. 新的内核版本已安装到 /boot 目录，但系统尚未切换使用它。"
    echo "2. 请立即执行重启命令来使新内核生效：\n"
    read -r -p "是否现在执行 'sudo reboot' 重启系统？ (y/N): " confirm_reboot
    if [[ "$confirm_reboot" =~ ^[Yy]$ ]]; then
        echo ""
        echo "--- 正在重启系统，请在下次启动时选择新的内核版本 ---"
        sudo reboot
    else
        echo ""
        echo "操作完成。您可以手动执行 'sudo update-grub' 或编辑 /etc/default/grub 来确保新内核默认加载。"
    fi

    # 最终清理工作
    echo -e "\n[CLEANUP] Removing temporary build directory: $TEMP_DIR"
    rm -rf "$TEMP_DIR"
}


# =========================================
# MAIN EXECUTION FLOW
# =========================================
if ! check_dependencies; then exit 1; fi
download_and_extract || exit 1
configure_kernel || exit 1
compile_kernel || exit 1
install_kernel || exit 1
cleanup_and_reboot