#!/usr/bin/bash
# Updates Fedora and NVIDIA together using the signed Universal Blue drivers.
# Usage: sudo ./script.sh            install or update everything
#        sudo ./script.sh --restore  go back to the RPM Fusion NVIDIA driver
#        --auto                      used by the daily timer: no questions, notifies when a reboot is needed
# For Fedora Workstation on x86_64 with Secure Boot and an NVIDIA GPU supported
# by the open kernel modules (GTX 16xx, RTX 20xx and newer).
# On CachyOS it runs the official CachyOS Easy Anti-Cheat setup (eac-setup) instead.
# Run with sudo. Reboot manually once the update has finished.
# Based on the original script by AmilieFOSS (https://fixupx.com/AmilieFOSS), with sincere thanks.

set -euo pipefail
shopt -s nullglob
export LC_ALL=C

error() {
    echo "Error: $*" >&2
    exit 1
}

if [ "$EUID" -ne 0 ]; then
    error "Please run this script with sudo."
fi

if [ "$(uname -m)" != "x86_64" ]; then
    error "This script is only for x86_64 Fedora, it is not intended for ARM. Running on Apple Silicon? Try Aurora Linux."
fi

# Prevent two updates running at the same time.
exec 9>/run/lock/ublue-nvidia-update.lock
flock -n 9 || error "An update is already running."

auto=no
state=/var/lib/fortnite-on-linux
installed_script=/usr/local/sbin/fortnite-on-linux
unit=fortnite-on-linux-update
repo_override=/etc/dnf/repos.override.d/80-fortnite-on-linux.repo
# Packages tied to one kernel version. Not kernel*: that would also hold back kernel-headers and kernel-tools.
kernel_packages=kernel,kernel-core,kernel-modules,kernel-modules-core,kernel-modules-extra,kernel-devel,kernel-devel-matched

# CachyOS ships its own signed EAC kernel with NVIDIA modules and a setup tool, so hand over to it.
distro=$(. /etc/os-release && echo "${ID:-} ${ID_LIKE:-}")
if [[ " $distro " == *" cachyos "* ]] || { command -v pacman >/dev/null && [ -f /etc/pacman.d/cachyos-mirrorlist ]; }; then
    [ "${1:-}" = "" ] || error "Option '$1' is for Fedora only. On CachyOS run without options."
    echo "CachyOS detected, using the official CachyOS Easy Anti-Cheat setup (eac-setup)."
    echo "Guide: https://wiki.cachyos.org/configuration/easy_anti_cheat/"
    # eac-setup needs cachyos-settings 1.4.4 or newer, and Arch only supports full upgrades.
    pacman -Syu --needed cachyos-settings
    eac-setup
    echo "When Secure Boot is on, start a gaming session with: sudo eac-setup boot"
    exit 0
fi
command -v dnf >/dev/null || error "Only Fedora and CachyOS are supported, see https://deandark.me/FortniteOnLinux/#other-distros"
command -v podman >/dev/null || error "podman is missing, install it with: dnf install podman"

# PCI vendor 0x10de is NVIDIA, class 0x03xxxx is a display controller.
nvidia_gpu=no
for dev in /sys/bus/pci/devices/*; do
    [ "$(cat "$dev/vendor")" = 0x10de ] && [[ "$(cat "$dev/class")" == 0x03* ]] && nvidia_gpu=yes
done
[ "$nvidia_gpu" = yes ] || error "No NVIDIA GPU found. AMD and Intel GPUs do not need this script, see https://deandark.me/FortniteOnLinux/#amd"

# Asks the firmware to trust a key on the next boot, with a one-time password.
request_enrollment() {
    local hash_file
    hash_file=$(mktemp)
    mokutil --generate-hash="$2" > "$hash_file"
    mokutil --import "$1" --hash-file "$hash_file" || { rm -f "$hash_file"; error "Could not request the key enrollment."; }
    rm -f "$hash_file"
}

confirm() {
    local answer
    [ "$auto" = no ] || error "$1 Needs an answer, run it by hand: sudo $installed_script"
    # Without a terminal the answer is no.
    read -rp "$1 [y/N] " answer < /dev/tty || answer=
    [[ "$answer" =~ ^[Yy]([Ee][Ss])?$ ]] || error "Canceled, nothing was changed."
}

# Daily timer plus a DNF override, so kernels from Fedora only arrive through this script,
# together with their NVIDIA driver. This covers dnf upgrade and GNOME Software.
setup_automatic() {
    [ "$auto" = no ] || return 0
    [ "$(readlink -f "$0")" = "$installed_script" ] || install -D -m 755 "$(readlink -f "$0")" "$installed_script"
    mkdir -p "${repo_override%/*}"
    printf '# Written by %s, removed by its --restore.\n[fedora]\nexcludepkgs=%s\n\n[updates*]\nexcludepkgs=%s\n\n# Keeps RPM Fusion from mixing its NVIDIA packages into the Universal Blue driver.\n[rpmfusion-nonfree*]\nexcludepkgs=*nvidia*\n' \
        "$installed_script" "$kernel_packages" "$kernel_packages" > "$repo_override"
    cat > "/etc/systemd/system/$unit.service" <<EOF
[Unit]
Description=Update Fedora, the kernel and the Universal Blue NVIDIA driver
Wants=network-online.target
After=network-online.target
ConditionACPower=true

[Service]
Type=oneshot
ExecStart=$installed_script --auto
TimeoutStartSec=2h
Nice=10
IOSchedulingClass=idle
EOF
    cat > "/etc/systemd/system/$unit.timer" <<EOF
[Unit]
Description=Daily update of Fedora and the Universal Blue NVIDIA driver

[Timer]
OnCalendar=daily
RandomizedDelaySec=2h
Persistent=true

[Install]
WantedBy=timers.target
EOF
    systemctl daemon-reload
    systemctl enable --now "$unit.timer" 2>/dev/null
    echo "Automatic daily updates are on, logs: journalctl -u $unit"
    echo "Fedora kernels now come only through this script, also in GNOME Software and dnf upgrade."
}

remove_automatic() {
    systemctl disable --now "$unit.timer" 2>/dev/null || true
    rm -f "/etc/systemd/system/$unit.service" "/etc/systemd/system/$unit.timer" "$repo_override" "$installed_script"
    rm -rf "$state"
    systemctl daemon-reload
    podman rmi -f "ghcr.io/ublue-os/akmods-nvidia-open:main-$(rpm -E %fedora)" >/dev/null 2>&1 || true
}

# Desktop notification for everyone logged in, used by the timer.
notify_users() {
    local uid user
    command -v notify-send >/dev/null || return 0
    while read -r uid user _; do
        [ -S "/run/user/$uid/bus" ] || continue
        runuser -u "$user" -- env DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$uid/bus" \
            notify-send -u critical -a "Fortnite on Linux" "$1" "$2" || true
    done < <(loginctl list-users --no-legend)
}

restore_rpmfusion() {
    local akmods_key=/etc/pki/akmods/certs/public_key.der kernel ublue shared only key_status name have want
    local reinstall=() upgrade=() downgrade=() actions=() rpmfusion_repos
    dnf repolist --enabled 2>/dev/null | grep -q '^rpmfusion-nonfree ' \
        || error "The RPM Fusion nonfree repository is not enabled, see https://rpmfusion.org/Configuration"
    # Packages installed from local files (@commandline) are the Universal Blue ones and old akmods builds.
    mapfile -t ublue < <(dnf repoquery -q --installed --qf '%{name} %{from_repo}\n' '*nvidia*' \
        | awk '$2 == "@commandline" || $2 == "fedora-nvidia" { print $1 }' | sort -u)
    [ "${#ublue[@]}" -gt 0 ] || error "The Universal Blue NVIDIA driver is not installed."
    kernel=$(grubby --default-kernel)
    kernel=${kernel#/boot/vmlinuz-}

    # RPM Fusion ships some packages under the same names. Those are swapped for the
    # RPM Fusion build instead of removed, because DNF cannot remove and install one name together.
    rpmfusion_repos=(--repo='rpmfusion-nonfree*' --setopt=disable_excludes='rpmfusion-nonfree*')
    mapfile -t shared < <(dnf repoquery -q "${rpmfusion_repos[@]}" --qf '%{name}\n' "${ublue[@]}" | sort -u)
    mapfile -t only < <(printf '%s\n' "${ublue[@]}" | grep -vxF -f <(printf '%s\n' "${shared[@]}") || true)
    for name in "${shared[@]}"; do
        have=$(rpm -q --qf '%{VERSION}-%{RELEASE}\n' "$name" | head -1)
        want=$(dnf repoquery -q "${rpmfusion_repos[@]}" --latest-limit=1 --qf '%{version}-%{release}\n' "$name" | head -1)
        if [ "$have" = "$want" ]; then
            reinstall+=("$name")
        elif [ "$(printf '%s\n' "$have" "$want" | sort -V | tail -1)" = "$want" ]; then
            upgrade+=("$name")
        else
            downgrade+=("$name")
        fi
    done
    actions=(--action=install akmod-nvidia xorg-x11-drv-nvidia-cuda "kernel-devel-$kernel")
    [ "${#only[@]}" -eq 0 ] || actions+=(--action=remove "${only[@]}")
    # --from-repo applies to every item after it.
    [ "${#shared[@]}" -eq 0 ] || actions+=(--from-repo=rpmfusion-nonfree,rpmfusion-nonfree-updates)
    [ "${#reinstall[@]}" -eq 0 ] || actions+=(--action=reinstall "${reinstall[@]}")
    [ "${#upgrade[@]}" -eq 0 ] || actions+=(--action=upgrade "${upgrade[@]}")
    [ "${#downgrade[@]}" -eq 0 ] || actions+=(--action=downgrade "${downgrade[@]}")

    echo "These NVIDIA packages will be removed or replaced: ${ublue[*]}"
    echo "Then the RPM Fusion driver is installed and built for kernel $kernel."
    confirm "Switch back to the RPM Fusion NVIDIA driver?"
    remove_automatic

    dnf --refresh --setopt=installonly_limit=0 -y do --allowerasing "${actions[@]}"
    # akmods signs with this key, so it has to exist before the build.
    [ -s "$akmods_key" ] || kmodgenca -a
    echo "Building the NVIDIA module for kernel $kernel, this takes a few minutes. Don't reboot yet."
    akmods --force --kernels "$kernel"
    modinfo -k "$kernel" -F version nvidia >/dev/null 2>&1 \
        || error "The RPM Fusion NVIDIA module did not build, don't reboot yet. Logs: /var/cache/akmods/nvidia/"

    echo "Back on the RPM Fusion NVIDIA driver."
    key_status=$(mokutil --test-key "$akmods_key" 2>&1 || true)
    case "$key_status" in
        *"is already enrolled"*) echo "Reboot when ready." ;;
        *"is already in the enrollment request"*) echo "Reboot and enroll the RPM Fusion key on the blue MOK Manager screen." ;;
        *)
            request_enrollment "$akmods_key" rpmfusion
            echo "Reboot. On the blue MOK Manager screen choose: Enroll MOK, Continue, Yes, type the password 'rpmfusion', Reboot."
            echo "Until then the NVIDIA driver will not load."
            ;;
    esac
    echo "Note: games with Easy Anti-Cheat for Linux, like Fortnite, do not start while the RPM Fusion key is enrolled."
}

case "${1:-}" in
    "") ;;
    --restore) restore_rpmfusion; exit 0 ;;
    --auto) auto=yes ;;
    *) error "Unknown option '$1'. Run without options to install or update, or with --restore to go back to RPM Fusion." ;;
esac

key=/etc/pki/ublue/public_key.der
key_url=https://raw.githubusercontent.com/ublue-os/akmods/main/certs/public_key.der
key_sha256=4e5c68474cb133fd8984d9599762cece9100c3e6cd8a9709aeaabd85dd9e70d1
mok_password=universalblue
old_kernel=$(uname -r)
# The driver can be missing after removing the RPM Fusion packages.
old_driver=$(modinfo -F version nvidia 2>/dev/null || echo none)
fedora=$(rpm -E %fedora)

# Check that the current setup is working before changing anything.
mokutil --sb-state | grep -q '^SecureBoot enabled' || error "Secure Boot is disabled."

# Download the Universal Blue key and enroll it on the first run.
if [ ! -f "$key" ]; then
    mkdir -p "${key%/*}"
    curl -fsSL -o "$key.tmp" "$key_url" || error "Could not download the Universal Blue key."
    mv "$key.tmp" "$key"
fi
echo "$key_sha256  $key" | sha256sum -c --quiet || error "$key has the wrong checksum, delete it and run again."

enroll_steps="Reboot now. On the blue MOK Manager screen choose: Enroll MOK, Continue, Yes, type the password '$mok_password', Reboot. Then run this script again."
key_status=$(mokutil --test-key "$key" 2>&1 || true)
case "$key_status" in
    *"is already enrolled"*)
        echo "Universal Blue key is enrolled."
        ;;
    *"is already in the enrollment request"*)
        echo "Universal Blue key is waiting for enrollment. $enroll_steps"
        exit 0
        ;;
    *)
        [ "$auto" = no ] || error "Universal Blue key is not enrolled, run by hand: sudo $installed_script"
        request_enrollment "$key" "$mok_password"
        echo "Universal Blue key enrollment requested. $enroll_steps"
        exit 0
        ;;
esac

# Easy Anti-Cheat (Fortnite) refuses to start while any MOK it does not know is enrolled.
mapfile -t other_keys < <(mokutil --list-enrolled 2>/dev/null | sed -nE 's/^ *Subject:.*CN=([^,/]+).*/\1/p' | grep -vxE 'fedoraca|ublue kernel' || true)
if [ "${#other_keys[@]}" -gt 0 ]; then
    echo "Warning: other Machine Owner Keys are enrolled: ${other_keys[*]}"
    echo "Games with Easy Anti-Cheat for Linux, like Fortnite, will not start until they are removed:"
    echo "  find their files with 'cd /tmp && mokutil --export', remove each with 'sudo mokutil --delete /tmp/MOK-000N.der', then reboot."
fi

if [ "$old_driver" != none ] && [ "$(modinfo -F signer nvidia)" != "ublue kernel" ]; then
    echo "Current NVIDIA driver is not signed by Universal Blue, switching to it."
fi
[ -f "/boot/vmlinuz-$old_kernel" ] || error "Current kernel file is missing."
[ -f "/boot/initramfs-$old_kernel.img" ] || error "Current initramfs is missing."

# The RPM Fusion driver is replaced in the same DNF transaction as the install.
mapfile -t rpmfusion < <(rpm -qa --qf '%{NAME}\n' akmod-nvidia 'xorg-x11-drv-nvidia*' | sort -u)
if [ "${#rpmfusion[@]}" -gt 0 ]; then
    echo "These installed NVIDIA packages will be removed: ${rpmfusion[*]}"
    # Asked before the download, so a "no" costs nothing.
    confirm "Remove the current NVIDIA drivers and switch to Universal Blue?"
fi

# The kernel and NVIDIA packages are left out here: below they are updated together,
# to the newest kernel Universal Blue has built the driver for.
echo "Updating the rest of Fedora."
# Not *nvidia*: that would also hold back nvidia-gpu-firmware and with it linux-firmware.
dnf --refresh -y upgrade --exclude="$kernel_packages",'kmod-nvidia*,akmod-nvidia*,nvidia-driver*,nvidia-kmod-common,nvidia-modprobe,nvidia-persistenced,nvidia-settings,nvidia-xconfig,nvidia-libXNVCtrl*,libnvidia-*,xorg-x11-nvidia*,xorg-x11-drv-nvidia*'

# A driver installed for a kernel that is not running yet means the last update waits for a reboot.
pending=$(rpm -ql kmod-nvidia 2>/dev/null | sed -nE 's@^/(usr/)?lib/modules/([^/]+)/.*@\2@p' | sort -u || true)
if [ -n "$pending" ] && [ "$pending" != "$old_kernel" ]; then
    echo "The last update for kernel $pending waits for a reboot. Reboot, then the driver updates continue."
    setup_automatic
    exit 0
fi

# Download the new drivers into a temporary folder.
folder=$(mktemp -d /var/tmp/ublue-nvidia.XXXXXXXX)
container=""
updating=no

cleanup() {
    if [ "$updating" = yes ]; then
        grubby --set-default "/boot/vmlinuz-$old_kernel" || echo "Could not restore the old boot entry."
        echo "Update did not finish. Check the drivers before rebooting."
    fi
    if [ -n "$container" ]; then
        podman rm -f "$container" >/dev/null 2>&1 || true
    fi
    rm -rf -- "$folder"
}
trap cleanup EXIT

image="ghcr.io/ublue-os/akmods-nvidia-open:main-$fedora"
echo "Checking for new Universal Blue NVIDIA drivers on ghcr.io."
# The image stays cached (about 800 MB), so an unchanged image costs only a small request.
previous=$(podman image inspect --format '{{.Id}}' "$image" 2>/dev/null || true)
podman pull "$image"
image_id=$(podman image inspect --format '{{.Id}}' "$image")
if [ -n "$previous" ] && [ "$previous" != "$image_id" ]; then
    podman rmi "$previous" >/dev/null 2>&1 || true
fi
if [ "$(cat "$state/image" 2>/dev/null || true)" = "$image_id" ]; then
    echo "Already up to date."
    setup_automatic
    exit 0
fi
container=$(podman create "$image" /bin/true)
podman cp "$container":/rpms "$folder/"

# Find out which kernel the new driver was built for.
packages=("$folder"/rpms/kmods/kmod-nvidia-*.rpm)

[ "${#packages[@]}" -eq 1 ] || error "Could not find a single NVIDIA kernel package."
kmod=${packages[0]}

new_kernel=$(rpm -qpl "$kmod" | sed -nE 's@^/(usr/)?lib/modules/([^/]+)/.*nvidia\.ko(\..*)?$@\2@p' | sort -u)
new_driver=$(rpm -qp --qf '%{VERSION}' "$kmod")
[[ "$new_kernel" =~ ^[0-9][A-Za-z0-9._+-]*\.x86_64$ ]] || error "Could not find the matching kernel version."
[ "$(rpm -qp --qf '%{NAME}' "$kmod")" = kmod-nvidia ] || error "Unexpected package name."

echo "Current kernel: $old_kernel"
echo "New kernel:     $new_kernel"
echo "Current NVIDIA: $old_driver"
echo "New NVIDIA:     $new_driver"

# Make sure the download isn't older than what we already have.
[ "$(printf '%s\n' "$old_kernel" "$new_kernel" | sort -V | tail -1)" = "$new_kernel" ] || error "Universal Blue has not built the driver for kernel $old_kernel yet. Try again in a day or two."
if [ "$old_driver" != none ]; then
    [ "$(printf '%s\n' "$old_driver" "$new_driver" | sort -V | tail -1)" = "$new_driver" ] || error "Downloaded driver is older."
fi

if [ "$old_kernel" = "$new_kernel" ] && [ "$old_driver" = "$new_driver" ]; then
    echo "Already up to date."
    mkdir -p "$state"
    echo "$image_id" > "$state/image"
    setup_automatic
    exit 0
fi

# Check the driver libraries all have the same version.
drivers=("$folder"/rpms/nvidia/*.rpm)
[ "${#drivers[@]}" -gt 0 ] || error "NVIDIA driver packages are missing."
for package in "${drivers[@]}"; do
    [ "$(rpm -qp --qf '%{VERSION}' "$package")" = "$new_driver" ] || error "NVIDIA package versions do not match."
done

# Check the five kernel modules before installing them.
mkdir "$folder/inspect"
(cd "$folder/inspect"; rpm2cpio "$kmod" | cpio -idm --quiet --no-absolute-filenames)
mapfile -d '' -t modules < <(find "$folder/inspect" -type f -name 'nvidia*.ko*' -print0)
[ "${#modules[@]}" -eq 5 ] || error "Expected five NVIDIA modules."
for module in "${modules[@]}"; do
    [ "$(modinfo -F signer "$module")" = "ublue kernel" ] || error "Unexpected module signer."
    [[ "$(modinfo -F vermagic "$module")" == "$new_kernel "* ]] || error "Module is for a different kernel."
done

# Secure Boot will check the actual signatures when the modules load.
if rpm -q "kmod-nvidia-$new_kernel" >/dev/null 2>&1; then
    error "An old RPM Fusion module conflicts with the new driver."
fi

# Install the matching kernel and drivers in one DNF transaction.
# DNF asks for confirmation and stops if a package is missing or conflicts.
kernels=("kernel-$new_kernel" "kernel-core-$new_kernel" "kernel-modules-core-$new_kernel" "kernel-modules-$new_kernel")
if rpm -q "kernel-modules-extra-$old_kernel" >/dev/null 2>&1; then
    kernels+=("kernel-modules-extra-$new_kernel")
fi

echo "Installing the kernel and NVIDIA drivers, don't reboot yet"
updating=yes
actions=(--action=install "${kernels[@]}" "$kmod" "${drivers[@]}" nvidia-driver-selinux)
[ "${#rpmfusion[@]}" -eq 0 ] || actions+=(--action=remove "${rpmfusion[@]}")
# nvidia-kmod-common needs nvidia-driver-selinux, which only the negativo17 repo has.
dnf --refresh --setopt=installonly_limit=0 --setopt=disable_excludes='fedora,updates*' --disable-repo='rpmfusion-nonfree*' \
    --repofrompath="fedora-nvidia,https://negativo17.org/repos/nvidia/fedora-$fedora/x86_64/" \
    --setopt=fedora-nvidia.gpgkey=https://negativo17.org/repos/RPM-GPG-KEY-slaanesh \
    -y do --allowerasing "${actions[@]}"

grubby --set-default "/boot/vmlinuz-$old_kernel"

# Check the installed driver and prepare the new kernel for boot.
depmod -a "$new_kernel"
[ "$(modinfo -k "$new_kernel" -F signer nvidia)" = "ublue kernel" ] || error "Installed driver has the wrong signer."
[ "$(modinfo -k "$new_kernel" -F version nvidia)" = "$new_driver" ] || error "Installed driver has the wrong version."
dracut --force --kver "$new_kernel"
grubby --set-default "/boot/vmlinuz-$new_kernel"
updating=no
mkdir -p "$state"
echo "$image_id" > "$state/image"

echo "Update finished! Kernel: $new_kernel, NVIDIA: $new_driver"
echo "Reboot when ready, then run nvidia-smi."
echo "The new kernel is the default. The old kernel is kept, but it has no NVIDIA driver anymore."
echo "To boot the old kernel by default: grubby --set-default /boot/vmlinuz-$old_kernel"
setup_automatic
[ "$auto" = no ] || notify_users "NVIDIA driver updated" "Reboot before starting games. Kernel $new_kernel, NVIDIA $new_driver."
