#!/bin/bash

function install() {
    local cmdindicator="GRUB_CMDLINE_LINUX_DEFAULT=\"";
    local config="nvidia_drm.fbdev=1";

    # According to: https://wiki.archlinux.org/title/NVIDIA/Tips_and_tricks
    {
        echo "options nvidia NVreg_PreserveVideoMemoryAllocations=1";
        echo "options nvidia NVreg_TemporaryFilePath=/var/tmp";
    } | sudo tee /etc/modprobe.d/nvidia-power-management.conf > /dev/null;

    sudo systemctl enable \
        nvidia-suspend.service \
        nvidia-hibernate.service \
        nvidia-resume.service;

    if ! cat /etc/default/grub | grep "$cmdindicator.*$config" > /dev/null;
    then
        sudo sed -i /etc/default/grub \
            -e "/$cmdindicator/{" \
                -e "s/\($cmdindicator.*[^ ]\)\(\"\)/\1 \2/" \
                -e "s/\($cmdindicator.*\)\(\"\)/\1$config\2/" \
            -e "}" \
        ;
    fi;
}

install;