#!/bin/bash

# Check if bootctl is available
if ! command -v bootctl &>/dev/null; then
    echo "Error: bootctl command not found. Unable to determine the current bootloader."
    exit 1
fi

# Get the current bootloader from bootctl status
bootloader=$(bootctl status 2>/dev/null | grep -i 'Product' | awk '{print $2}')

# Provide feedback on the detected bootloader
if [[ -z "$bootloader" ]]; then
    echo "Error: Unable to detect the bootloader using bootctl. Please check the system configuration."
    exit 1
fi

echo "The system is using $bootloader as the bootloader."

# Check if the bootloader is GRUB and proceed with installation if necessary
if [[ "$bootloader" == "GRUB" ]]; then
    echo "GRUB bootloader detected. Installing or reconfiguring GRUB..."

    # Ensure grub-install exists and is executable
    if ! command -v grub-install &>/dev/null; then
        echo "Error: grub-install command not found. Please install GRUB."
        exit 1
    fi

    # Execute the grub-install command with necessary parameters
    sudo grub-install --target=x86_64-efi \
                      --efi-directory=/boot/efi \
                      --bootloader-id=snigdhaos \
                      --disable-shim-lock \
                      --removable

    # Check the result of the grub-install command
    if [[ $? -eq 0 ]]; then
        echo "GRUB installation successful."
    else
        echo "Error: GRUB installation failed. Please check the logs for more details."
        exit 1
    fi
else
    echo "The system is not using GRUB as the bootloader. No action will be taken."
fi

exit 0
