#!/usr/bin/env sh
#
# SPDX-FileCopyrightText: 2026 Ethan Masse <guitaristocrat@aol.com>
#
# SPDX-License-Identifier: CC-BY-SA-4.0 OR AGPL-3.0-or-later

# Prints some text, prefixed by the calling name of the script.
ME_X_ECHO_FN () {
	echo "("$(basename $0)")" $@;
}

# Run a specific command with a pretty print interface and an
# optional explaining message to be printed beforehand.
ME_X_RUNCMD_FN () {
	if [ ""x != "$2"x ]; then
		ME_X_ECHO_FN "$2"
	fi
	ME_X_ECHO_FN "Running '$1' ..." &&
	eval " $1" || return 1;
}

# Uncomment below to fully clean the dnf cache before doing anything else.
# This can help make the build more reproducible, but at the cost of
# increasing update time and pulling unnecessary bandwidth from
# all your enabled repositories every time the script is run.
#ME_X_RUNCMD_FN "sudo dnf --color=auto clean all" "Invalidating DNF cache:" &&

ME_X_RUNCMD_FN "sudo dnf --color=auto update --refresh" "Updating DNF packages:" &&
ME_X_RUNCMD_FN "sudo dnf --color=auto autoremove" "Removing unneeded DNF packages:" &&

# Use something like the below commented line to reinstall kernel modules.
# This helps ensure your kernel modules are installed at the highest available
# version before running the rebuild commands below. This can avoid bugs
# due to kernel/module version mismatching.
#ME_X_RUNCMD_FN "sudo dnf --color=auto reinstall akmod-nvidia kmod-nvidia libva-nvidia-driver xorg-x11-drv-nvidia xorg-x11-drv-nvidia-cuda-libs xorg-x11-drv-nvidia-kmodsrc xorg-x11-drv-nvidia-libs akmod-VirtualBox VirtualBox-kmodsrc VirtualBox" "Reinstalling some packages with kernel modules:" &&

# Below line requires akmods. I recommend installing it.
# It's harmless to install akmods on systems that don't need it.
# In that case, this command will just quickly exit with nothing to do.
ME_X_RUNCMD_FN "sudo akmods --verbose --rebuild --force" "Rebuilding kernel modules (stage 1):" &&

ME_X_RUNCMD_FN "sudo dracut --verbose --regenerate-all --force" "Rebuilding kernel modules (stage 2):" &&

# Change the below location from /boot/grub2/grub.cfg to wherever
# your system stores its grub configuration file. This is the Fedora default.
ME_X_RUNCMD_FN "sudo grub2-mkconfig -o /boot/grub2/grub.cfg" "Updating grub.cfg:" &&

# Below two lines are for systems that use flatpak.
# They can be commented out/removed on servers or other
# systems that don't use flatpak, but for systems that do,
# this mimics e.g. KDE Discover's behavior.
ME_X_RUNCMD_FN "flatpak update --verbose" "Updating flatpaks:" &&
ME_X_RUNCMD_FN "flatpak uninstall --unused --verbose" "Removing unneeded flatpaks:" &&

ME_X_ECHO_FN "Everything completed successfully! :)" &&
exit 0 || exit 1;

