#!/bin/bash

#  2023-2023, Rafael Ruscher <rruscher@gmail.com>
#  2023-2023, Bruno Gonçalves <www.biglinux.com.br>
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions
#  are met:
#  1. Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
#  2. Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
#  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
#  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
#  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
#  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
#  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
#  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
#  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


# Temporarily adds support for the nvidia 580 driver until it is directly available in the mhwd-db package
if ! [[ -e /var/lib/mhwd/db/pci/graphic_drivers/nvidia-580xx ]]; then
    if ! [[ -e /var/lib/mhwd/db/pci/graphic_drivers/nvidia-580xx-big ]]; then
        cp -R /var/lib/mhwd/db/pci/graphic_drivers/nvidia-575xx /var/lib/mhwd/db/pci/graphic_drivers/nvidia-580xx-big
        cp -R /var/lib/mhwd/db/pci/graphic_drivers/hybrid-amd-nvidia-575xx-prime /var/lib/mhwd/db/pci/graphic_drivers/hybrid-amd-nvidia-580xx-prime-big
        cp -R /var/lib/mhwd/db/pci/graphic_drivers/hybrid-intel-nvidia-575xx-prime /var/lib/mhwd/db/pci/graphic_drivers/hybrid-intel-nvidia-580xx-prime-big
        
        sed -i 's|575|580|g' /var/lib/mhwd/db/pci/graphic_drivers/nvidia-580xx-big/MHWDCONFIG /var/lib/mhwd/db/pci/graphic_drivers/hybrid-amd-nvidia-580xx-prime-big/MHWDCONFIG /var/lib/mhwd/db/pci/graphic_drivers/hybrid-intel-nvidia-580xx-prime-big/MHWDCONFIG
    else
        rm -Rf /var/lib/mhwd/db/pci/graphic_drivers/nvidia-580xx-big /var/lib/mhwd/db/pci/graphic_drivers/hybrid-amd-nvidia-580xx-prime-big /var/lib/mhwd/db/pci/graphic_drivers/hybrid-intel-nvidia-580xx-prime-big
    fi
fi



# Add xanmod in mhwd-kernel
if ! grep -q linux-xanmod /usr/bin/mhwd-kernel; then
    sed -i 's/\^linux\[0-9]\[0-9]?(\[0-9])\$/^linux[0-9][0-9]?([0-9])$|^linux-xanmod$|^linux-xanmod-lts$/g' /var/lib/mhwd/scripts/mhwd
    sed -i 's/\^linux\[0-9]\[0-9]?(\[0-9])\$/^linux[0-9][0-9]?([0-9])$|^linux-xanmod$|^linux-xanmod-lts$/g' /usr/bin/mhwd-kernel
    
    sed -i 's/current="linux$major$minor"/if uname -r | grep xanmod.*lts >\/dev\/null; then current="linux-xanmod-lts"; elif uname -r | grep xanmod >\/dev\/null; then current="linux-xanmod";  else current="linux$major$minor"; fi/g' /usr/bin/mhwd-kernel
fi

# Not try in in obsolete kernel
sed -i 's#KERNELS=$(pacman -Qqs .*linux-xanmod-lts$")#KERNELS=$(pacman -Qqs "^linux[0-9][0-9]?([0-9])$|^linux-xanmod$|^linux-xanmod-lts$")#' /var/lib/mhwd/scripts/mhwd

# Dont stop if fail to remove package ( Solve problem to install with conky package on iso )
sed -i '360s/exit 1/exit 0/' /var/lib/mhwd/scripts/mhwd

# Folder with scripts
cd /var/lib/mhwd/db/pci/graphic_drivers/

# Folders with MHWDCONFIG to change
Folders="hybrid-amd-nvidia-470xx-prime
hybrid-amd-nvidia-prime
hybrid-intel-nvidia-470xx-prime
hybrid-intel-nvidia-prime"

for folder in $Folders; do
    # Add switcheroo-control to files
    if ! grep -q 'switcheroo-control' $folder/MHWDCONFIG; then
        sed -i 's|^DEPENDS="|DEPENDS="switcheroo-control |g' $folder/MHWDCONFIG
    fi
done

# if [[ -e /etc/udev/rules.d/80-nvidia-pm.rules ]]; then
#     if grep -q 'ACTION=="add", SUBSYSTEM=="pci", ATTR{vendor}=="0x10de", ATTR{class}=="0x040300", ATTR{remove}="1"' /etc/udev/rules.d/80-nvidia-pm.rules; then
#         rm -f /etc/udev/rules.d/80-nvidia-pm.rules
#     fi
# fi


# if [[ $(lspci | grep -iE "VGA|3D" | wc -l) > 1 && -n $(lsmod | grep nvidia_drm) ]]; then
#     sed -i 's|nvidia-drm.modeset=1||g' /etc/default/grub
#     nvidia-drm modeset=0
# fi


# Add file to enable power manager for nvidia
# if [[ ! -e /etc/modprobe.d/nvidia-pm.conf ]]; then
# 
# read -d $'' ShowText <<EOF
# options nvidia "NVreg_DynamicPowerManagement=0x02"
# EOF
# echo "$ShowText" >> /etc/modprobe.d/nvidia-pm.conf
# 
# fi

# Add file to enable power manager for nvidia
# Optimus manager not default used in BigLinux, but add good configuration just because we like make best system
if [[ ! -e /etc/optimus-manager/optimus-manager.conf ]]; then

mkdir -p /etc/optimus-manager/

read -d $'' ShowText <<EOF
[optimus]

# This parameter defines the method used to power switch the Nvidia card. See the documentation
# for a complete description of what each value does. Possible values :
#
# - nouveau : load the nouveau module on the Nvidia card.
# - bbswitch : power off the card using the bbswitch module (requires the bbswitch dependency).
# - acpi_call : try various ACPI method calls to power the card on and off (requires the acpi_call dependency)
# - custom: use custom scripts at /etc/optimus-manager/nvidia-enable.sh and /etc/optimus-manager/nvidia-disable.sh
# - none : do not use an external module for power management. For some laptop models it's preferable to
#          use this option in combination with pci_power_control (see below).
# switching=none

# Enable PCI power management in "integrated" mode.
# This option is incompatible with acpi_call and bbswitch, so it will be ignored in those cases.
# pci_power_control=no
pci_power_control=yes

# Remove the Nvidia card from the PCI bus.
# May prevent crashes caused by power switching.
# Ignored if switching=nouveau or switching=bbswitch.
# pci_remove=no

# Reset the Nvidia card at the PCI level before reloading the nvidia module.
# Ensures the card is in a fresh state before reloading the nvidia module.
# May fix some switching issues. Possible values :
#
# - no : does not perform any reset
# - function_level : perform a light "function-level" reset
# - hot_reset : perform a "hot reset" of the PCI bridge. ATTENTION : this method messes with the hardware
#         directly, please read the online documentation of optimus-manager before using it.
#         Also, it will perform a PCI remove even if pci_remove=no.
#
# pci_reset=no

# Automatically log out the current desktop session when switching GPUs.
# This feature is currently supported for the following DE/WM :
# GNOME, KDE Plasma, LXDE, Deepin, Xfce, i3, Openbox, AwesomeWM, bspwm, dwm, Xmonad, herbstluftwm
# If this option is disabled or you use a different desktop environment,
# GPU switching only becomes effective at the next graphical session login.
# auto_logout=yes

# GPU mode to use at computer startup.
# Possible values: nvidia, integrated, hybrid, auto, intel (deprecated, equivalent to integrated)
# "auto" is a special mode that auto-detects if the computer is running on battery
# and selects a proper GPU mode. See the other options below.
#startup_mode=integrated
startup_mode=hybrid
# GPU mode to select when startup_mode=auto and the computer is running on battery.
# Possible values: nvidia, integrated, hybrid, intel (deprecated, equivalent to integrated)
# startup_auto_battery_mode=integrated
# GPU mode to select when startup_mode=auto and the computer is running on external power.
# Possible values: nvidia, integrated, hybrid, intel (deprecated, equivalent to integrated)
# startup_auto_extpower_mode=nvidia

# [intel]

# Driver to use for the Intel GPU. Possible values : modesetting, intel
# To use the intel driver, you need to install the package "xf86-video-intel".
# driver=modesetting

# Acceleration method (corresponds to AccelMethod in the Xorg configuration).
# Only applies to the intel driver.
# Possible values : sna, xna, uxa
# Leave blank for the default (no option specified)
# accel=

# Enable TearFree option in the Xorg configuration.
# Only applies to the intel driver.
# Possible values : yes, no
# Leave blank for the default (no option specified)
# tearfree=

# DRI version. Possible values : 2, 3
# DRI=3

# Whether or not to enable modesetting for the nouveau driver.
# Does not affect modesetting for the Intel GPU driver !
# This option only matters if you use nouveau as the switching backend.
# modeset=yes

# [amd]

# Driver to use for the AMD GPU. Possible values : modesetting, amdgpu
# To use the amdgpu driver, you need to install the package "xf86-video-amdgpu".
# driver=modesetting

# Enable TearFree option in the Xorg configuration.
# Only applies to the amdgpu driver.
# Possible values : yes, no
# Leave blank for the default (no option specified)
# tearfree=

# DRI version. Possible values : 2, 3
# DRI=3

#[nvidia]

# Whether or not to enable modesetting. Required for PRIME Synchronization (which prevents tearing).
# modeset=yes

# Whether or not to enable the NVreg_UsePageAttributeTable option in the Nvidia driver.
# Recommended, can cause poor CPU performance otherwise.
# PAT=yes

# DPI value. This will be set using the Xsetup script passed to your login manager.
# It will run the command
# xrandr --dpi <DPI>
# Leave blank for the default (the above command will not be run).
# DPI=96

# If you're running an updated version of xorg-server (let's say to get PRIME Render offload enabled),
# the nvidia driver may not load because of an ABI version mismatch. Setting this flag to "yes"
# will allow the loading of the nvidia driver.
# ignore_abi=no

# Set to yes if you want to use optimus-manager with external Nvidia GPUs (experimental)
# allow_external_gpus=no

# Comma-separated list of Nvidia-specific options to apply.
# Available options :
# - overclocking : enable CoolBits in the Xorg configuration, which unlocks clocking options
#   in the Nvidia control panel. Note: does not work in hybrid mode.
# - triple_buffer : enable triple buffering.
# options=overclocking


# Enable Runtime D3 (RTD3) Power Management in the Nvidia driver. While in hybrid mode,
# this feature allows the Nvidia card to go into a low-power mode if it's not in use.
#
# IMPORTANT NOTES:
# - The feature is still experimental
# - It's only supported on laptops with a Turing GPU or above, and an Intel Coffee Lake CPU
# or above (not sure about the state of support for AMD CPUs).
# - if your Nvidia card also has an audio chip (for HDMI) or a USB port wired to it, they may not
# function properly while in low-power mode
#
# For more details, see
# https://download.nvidia.com/XFree86/Linux-x86_64/460.39/README/dynamicpowermanagement.html
#
# Available options:
# - no (the default): RTD3 power management is disabled.
# - coarse: the card only goes to low-power if no application is using it.
# - fine: the card is also allowed to go to low-power if applications are using it but have not
# actively submitted GPU work in some amount of time.
# dynamic_power_management=no

# The Nvidia driver handles power to the video memory separately from the rest of GPU.
# When dynamic_power_management=fine, this options controls the threshold of memory utilization
# (in Megabytes) under which the memory is put in a low-power state.
# Values over 200MB are ignored. Leave blank for the default (200MB).
# Setting this value to 0 keeps the memory powered at all times.
# dynamic_power_management_memory_threshold=
EOF

echo "$ShowText" >> /etc/optimus-manager/optimus-manager.conf

fi
