#!/bin/bash
#set -e
##################################################################################################################
# Author    : Erik Dubois
# Website   : https://www.erikdubois.be
# Website   : https://www.alci.online
# Website   : https://www.arcolinux.info
# Website   : https://www.arcolinux.com
# Website   : https://www.arcolinuxd.com
# Website   : https://www.arcolinuxb.com
# Website   : https://www.arcolinuxiso.com
# Website   : https://www.arcolinuxforum.com
##################################################################################################################
#
#   DO NOT JUST RUN THIS. EXAMINE AND JUDGE. RUN AT YOUR OWN RISK.
#
##################################################################################################################
#tput setaf 0 = black 
#tput setaf 1 = red 
#tput setaf 2 = green
#tput setaf 3 = yellow 
#tput setaf 4 = dark blue 
#tput setaf 5 = purple
#tput setaf 6 = cyan 
#tput setaf 7 = gray 
#tput setaf 8 = light blue
##################################################################################################################

# Disclaimer message
tput setaf 3;
echo "NO WARRANTY"
echo
echo "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,"
echo "EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF"
echo "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND"
echo "NONINFRINGEMENT."
echo "IN NO EVENT SHALL THE AUTHORS, COPYRIGHT HOLDERS, OR CONTRIBUTORS BE"
echo "LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN"
echo "ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF, OR IN"
echo "CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE"
echo "SOFTWARE."
echo "NO WARRANTY OR ASSURANCE, EITHER EXPRESS OR IMPLIED, IS MADE WITH"
echo "RESPECT TO THE PRODUCT PROVIDED UNDER OR BY VIRTUE OF THIS"
echo "AGREEMENT, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED WARRANTY OF"
echo "MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR"
echo "NON-INFRINGEMENT."
echo "NO WARRANTY IS GIVEN THAT THE SOFTWARE OR SERVICE WILL BE"
echo "ERROR-FREE, PERFORM IN AN UNINTERRUPTED MANNER, OR THAT ANY DEFECTS"
echo "OR ERRORS IN THE SOFTWARE OR SERVICE WILL BE CORRECTED."
echo "THE USER ASSUMES ALL RISKS AND RESPONSIBILITY FOR THE SELECTION OF"
echo "THE SOFTWARE TO ACHIEVE THEIR INTENDED RESULTS, AND FOR THE"
echo "INSTALLATION, USE, AND RESULTS OBTAINED FROM IT."
echo
echo "DISCLAIMER:"
echo "This script assists in changing the boot manager from GRUB to"
echo "either systemd-boot or rEFInd."
echo "Modifying your system's boot manager and configurations can be"
echo "hazardous and may result in a non-bootable system if not"
echo "executed correctly."
echo
echo "It is strongly recommended to have a full system backup and"
echo "a live USB available for system repair in case of any issues."
echo
echo "Do you wish to continue?"

# User confirmation
read -r -p "Please confirm with [Y/N]: " response
case "$response" in
    [yY][eE][sS]|[yY]) 
        echo "Proceeding with the boot manager change..."
        ;;
    *)
        echo "Operation cancelled by the user. Exiting script."
        exit 1
        ;;
esac
tput sgr0

echo
echo "Are you really sure?"
echo "This script may break your system"
echo "Resulting in an unbootable system!"

# User confirmation
read -r -p "Please confirm with [Y/N]: " response
case "$response" in
    [yY][eE][sS]|[yY]) 
        echo "Proceeding with the boot manager change..."
        ;;
    *)
        echo "Operation cancelled by the user. Exiting script."
        exit 1
        ;;
esac

if lsblk | grep -q "/boot/efi" ; then
    echo "/boot/efi is mounted."

	Online=0

	function check_connectivity() {

	    local test_ip
	    local test_count

	    test_ip="8.8.8.8"
	    test_count=1

	    if ping -c ${test_count} ${test_ip} > /dev/null; then
	       echo "You have internet connectivity"
	       Online=1
	    else
	       echo "You do not have internet connectivity"
	       Online=0
	    fi
	 }

	check_connectivity

	# if not online
	if [ $Online -eq 0 ] ; then
		echo
		echo "###############################################################################"
		echo "###                          YOU ARE NOT ONLINE                            ####"
		echo "###         WE ARE PINGING 8.8.8.8 TO TEST YOUR INTERNET CONNECTION        ####"
		echo "###                     WE NEED AN INTERNET CONNECTION                     ####"
		echo "###############################################################################"
		exit 1
	fi

	#function to check if a package is installed
	is_package_installed() {
	    if pacman -Q "$1" &> /dev/null; then
	        echo "Package $1 is installed."
	        return 0  # Success
	    else
	        echo "Package $1 is not installed."
	        return 1  # Failure
	    fi
	}

	echo "###############################################################################"
	echo "Removing other bootloaders"
	echo "###############################################################################"

	#GRUB GONE
	if is_package_installed archiso; then
	    echo "Removing archiso..."
	    sudo pacman -R archiso --noconfirm
	else
	    echo "Archiso is not installed, no need to remove."
	fi
	
	if is_package_installed arcolinux-bootloader-grub-git; then
	    echo "Removing arcolinux-bootloader-grub-git..."
	    sudo pacman -R arcolinux-bootloader-grub-git --noconfirm
	else
	    echo "Arcolinux-bootloader-grub-git is not installed, no need to remove."
	fi

	if is_package_installed arcolinux-grub-theme-vimix-git; then
	    echo "Removing arcolinux-grub-theme-vimix-git..."
	    sudo pacman -R arcolinux-grub-theme-vimix-git --noconfirm
	else
	    echo "Arcolinux-grub-theme-vimix-git is not installed, no need to remove."
	fi

	if is_package_installed grub-customizer; then
	    echo "Removing grub-customizer..."
	    sudo pacman -R --noconfirm grub-customizer 
	else
	    echo "Grub-customizer is not installed, no need to remove."
	fi

	#keep last
	if is_package_installed grub; then
	    echo "Removing grub..."
	    sudo pacman -R grub --noconfirm
	else
	    echo "Grub is not installed, no need to remove."
	fi

	if [ -d /boot/grub ]; then
		sudo rm -r /boot/grub
	fi

	if [ -f /etc/default/grub ]; then
		sudo rm /etc/default/grub*
	fi

	#REFIND GONE
	if is_package_installed arcolinux-bootloader-refind-git; then
	    echo "Removing arcolinux-bootloader-refind-git..."
	    sudo pacman -R arcolinux-bootloader-refind-git --noconfirm
	else
	    echo "Arcolinux-bootloader-refind-git is not installed, no need to remove."
	fi

	if is_package_installed arcolinux-refind-theme-arco-specs-git; then
	    echo "Removing arcolinux-refind-theme-arco-specs-git..."
	    sudo pacman -R arcolinux-refind-theme-arco-specs-git --noconfirm
	else
	    echo "Arcolinux-refind-theme-arco-git is not installed, no need to remove."
	fi

	#keep last
	if is_package_installed refind; then
	    echo "Removing refind..."
	    sudo pacman -R refind --noconfirm
	else
	    echo "Refind is not installed, no need to remove."
	fi

	echo "###############################################################################"
	echo "Installing the default systemd-boot from ArcoLinux"
	echo "###############################################################################"

	#REFIND GONE
	if is_package_installed kernel-install-mkinitcpio; then
	    echo "Removing kernel-install-mkinitcpio..."
	    sudo pacman -R kernel-install-mkinitcpio --noconfirm
	else
	    echo "Kernel-install-mkinitcpio is not installed, no need to remove."
	fi

	#sudo pacman -S --noconfirm kernel-install-mkinitcpio
	sudo pacman -S --noconfirm pacman-hook-kernel-install
	sudo pacman -S --noconfirm arcolinux-bootloader-systemd-boot-git

	sudo bootctl install

	if is_package_installed linux-cachyos; then
		# make sure we have chaotic repo there
		# Set the file path
		FILE="/etc/pacman.conf"

		# Search for "chaotic-aur" in the specified file
		if ! grep -q "chaotic-aur" "$FILE"; then
		    echo "Adding chaotic-aur repository to $FILE"
		    # Append the configuration for chaotic-aur to the file
		    {
		echo ""
		echo "#[chaotic-aur]"
		echo "#SigLevel = Required DatabaseOptional"
		echo "#Include = /etc/pacman.d/chaotic-mirrorlist"
		    } | sudo tee -a "$FILE"
		fi

		if grep -q "#\[chaotic-aur\]" /etc/pacman.conf; then
			echo "###############################################################################"
			echo "Activate the chaotic repo"
			echo "###############################################################################"
			sudo sed -i "s/#\[chaotic-aur\]/\[chaotic-aur\]/g" /etc/pacman.conf;
			sudo sed -i "s/#SigLevel = Required DatabaseOptional/SigLevel = Required DatabaseOptional/g" /etc/pacman.conf;
			sudo sed -i "s/#Include = \/etc\/pacman.d\/chaotic-mirrorlist/Include = \/etc\/pacman.d\/chaotic-mirrorlist/g" /etc/pacman.conf;
		fi

		sudo pacman -Sy
	fi
	
	# finding out what kernels we have

	# Define an array of possible kernels
	kernels=()

	# Variable to hold kernels and their headers to install
	packages_to_install=()

	for pkgbase_file in /usr/lib/modules/*/pkgbase; do
		# Read the kernel name from each pkgbase file
    	kernel_name=$(cat "$pkgbase_file")
    	kernels+=("$kernel_name")
	done

	# Variable to hold kernels and, if applicable, their headers for installation
	packages_to_install=()

	# Function to check if a package is already installed
	is_package_installed() {
	    pacman -Q "$1" &> /dev/null
	    return $?
	}

	# Loop through each specified kernel
	for kernel in "${kernels[@]}"; do
	    # Check if the kernel is installed
	    if is_package_installed "$kernel"; then
	        echo "$kernel is installed."
	        # Add the kernel to the installation list
	        packages_to_install+=("$kernel")
	        
	        # Check if the corresponding headers are installed
	        if is_package_installed "${kernel}-headers"; then
	            echo "${kernel}-headers are also installed. Adding to the list."
	            # Add the headers to the installation list
	            packages_to_install+=("${kernel}-headers")
	        fi
	    fi
	done

	# Check if any kernels or headers were added to the list and proceed with reinstallation
	if [ ${#packages_to_install[@]} -gt 0 ]; then
	    echo "Reinstalling the following kernels and their headers: ${packages_to_install[*]}"
	    sudo pacman -S --noconfirm "${packages_to_install[@]}"
	else
	    echo "No kernels or headers eligible for reinstallation were found."
	fi


	if [[ -f /boot/efi/loader/loader.conf ]];then
		sudo sed -i "s/#timeout 3/timeout 3/g" /boot/efi/loader/loader.conf
	fi

	if [[ -f /boot/efi/loader/loader.conf ]];then
		sudo sed -i "s/#console-mode keep/console-mode keep/g" /boot/efi/loader/loader.conf
	fi

	# Just checking if nvidia-dkms is installed else stop
	if pacman -Qi nvidia-dkms &> /dev/null; then
		# Check for each Wayland session file
		if 	[ -f /usr/share/wayland-sessions/hyprland.desktop ] || \
			[ -f /usr/share/wayland-sessions/sway.desktop ] || \
			[ -f /usr/share/wayland-sessions/wayfire.desktop ] || \
			[ -f /usr/share/wayland-sessions/plasma.desktop ] || \
			[ -f /usr/share/wayland-sessions/gnome-wayland.desktop ]; then
				sudo /usr/local/bin/arcolinux-nvidia-drm-wayland
		fi
	fi

	echo "systemd-boot" | sudo dd of="/bootloader"


	echo "###############################################################################"
	echo "Deactivate the chaotic repo"
	echo "###############################################################################"
	sudo sed -i 's/^\(\[chaotic-aur\]\)/#\1/; s/^\(SigLevel = Required DatabaseOptional\)/#\1/; s/^\(Include = \/etc\/pacman.d\/chaotic-mirrorlist\)/#\1/' /etc/pacman.conf
	echo
	echo "###############################################################################"
	echo "###                DONE - YOU CAN CLOSE THIS WINDOW                        ####"
	echo "###############################################################################"

else

	echo
	echo "###############################################################################"
	echo "###                YOU CAN NOT USE SYSTEMD-BOOT                            ####"
	echo "###                        KEEP USING GRUB                                 ####"
	echo "###        https://wiki.archlinux.org/title/Arch_boot_process              ####"
	echo "###############################################################################"
fi
