#!/bin/bash

# Exit codes
# 0 - All's well
# 1 - Not root
# 2 - Wrong parameters
# 3 - No driver available
# 7 - Card not supported
# 8 - No nvidia card found
# 10 - Source install detected

###original code from the solydXK project.
####MODIFICATIONS FOR MX by dolphin oracle
##depends: nvidia-detect-mx, nvidia-detect and cli-shell-utils
##modifications assume MX repos for the nvidia drivers
##legacy detection and substantial command assistance from kmathern & fehlix
##PRIMUS additions by farius and dolphin oracel
##

#add BitJam's soure cli-shell-utils
if [ -e "/usr/local/lib/cli-shell-utils/cli-shell-utils.bash" ]; then
	source /usr/local/lib/cli-shell-utils/cli-shell-utils.bash
else
	source /usr/lib/cli-shell-utils/cli-shell-utils.bash
fi

source gettext.sh
DEBIAN_VERSION_CODENAME=$(grep VERSION_CODENAME /etc/os-release|cut -d"=" -f2)
DEBIAN_VERSION_NUMBER=$(cat /etc/debian_version  |cut -d"." -f1)

VERSION="25.11.03"
ME=${0##*/}
CLI_PROG="ddm-mx"
LOCK_FILE="/run/lock/$CLI_PROG"
ERR_FILE="/dev/null"
LOG="/var/log/ddm.log"
BP_REPO="$DEBIAN_VERSION_CODENAME-backports"
BP_REPO_ADDRESS="deb http://ftp.debian.org/debian"
MX_TEST_REPO_ADDRESS="deb http://la.mxrepo.com/mx/testrepo/ $DEBIAN_VERSION_CODENAME test"
NVIDIA_DIRECT_REPO_ADDRESS="deb [signed-by=/usr/share/keyrings/cuda-archive-keyring.gpg] https://developer.download.nvidia.com/compute/cuda/repos/debian$DEBIAN_VERSION_NUMBER/x86_64/ /"
BACKPORTS_OVERRIDE=false
NVIDIA_OVERRIDE=false
NVIDIA_DETECT_MX="/usr/bin/nvidia-detect-mx"
if [ -x "./nvidia-detect-mx" ]; then
	NVIDIA_DETECT_MX="./nvidia-detect-mx"
fi

export TEXTDOMAINDIR=/usr/share/locale 
export TEXTDOMAIN="ddm-mx"

#blanket error message
UNKNOWN_ERROR=$(eval_gettext "Unknown error")
#error for options
OPTION_ERROR1=$(eval_gettext "Option-")
#tell that option needs an arguement
OPTION_ERROR2=$(eval_gettext "requires an argument.")
#must run as root or elevated
RUN_AS_ROOT=$(eval_gettext "Run as root")
#say what we are installing drivers for
INSTALL_DRIVERS_FOR=$(eval_gettext "Install drivers for: ")

NVIDIA_XCONFIG="nvidia-xconfig"

ARCH=$(dpkg --print-architecture)

#desktop name
DESKTOPFILENAME=$(gettext "Nvidia driver installer")
#desktop comment
DESKTOPFILECOMMENT=$(gettext "Install proprietary nvidia driver from repo")

main(){
# -------------------------------------------------------------------------
#get release info
source /etc/lsb-release
echo
echo "Distribution:  " $DISTRIB_ID
echo

# -------------------------------------------------------------------------

BUMBLEBEE_EXTRA_LIBS="primus primus-libs"

#if [ "$DISTRIB_ID" = "MX" ]; then
#     BUMBLEBEE_EXTRA_LIBS="virtualgl virtualgl-libs:i386"
#fi


BACKPORTS=false
PURGE=''
INSTALL=''
FORCEDRIVER=''
TEST=false
while getopts ":f:bNi:p:htd:cgr" opt; do
  case $opt in
    h)
      usage HELP
      ;;
    i)
      # Install
      INSTALL="$INSTALL$OPTARG"
      echo "INSTALL IS $INSTALL"
      ;;
    p)
      # Purge
      PURGE="$PURGE $OPTARG"
      ;;
    t)
      # Testing
      echo "TEST Install"
      TEST=true
      ;;
     d)
      # 0fd4 is 390-legacy
      echo "PCIID $OPTARG"
      PCIID="$OPTARG"
      ;;
    b)
      # off debian backports repo
      BACKPORTS_OVERRIDE=true
      ;;
     N)
      #offer nvidia developer repo 
      NVIDIA_OVERRIDE=true
      FORCEDRIVER=nvidia-driver
      ;;
    c) #force create of 20-nvidia.conf file
    	create_20_nvidiaconf
    	exit 0
    	;;
    f)
      # Testing
      FORCEDRIVER="$FORCEDRIVER$OPTARG"
      echo "FORCE DRIVER is $FORCEDRIVER"
      ;;
    g)
      # add nvidia grub and module configurations
      add_nvidia_module_config
      exit 0
      ;;
    r)
      # remove nvidia grub and module configurations
      remove_nvidia_module_config
      exit 0
      ;;
    \?)
      # Invalid option: start GUI
      #launch_gui $@
      echo $(eval_gettext "Invalid option") | tee -a $LOG
      exit 0
      ;;
    :)
      echo $OPTIONERROR1$OPTARG $OPTION_ERROR2 | tee -a $LOG
      exit 2
      ;;
    *)
      # Unknown error: start GUI
      #launch_gui $@
      #not a legal option
      echo $(eval_gettext "Invalid option") | tee -a $LOG
      exit 0
      ;;
  esac
done

# Is there anything to do?
if [ "$INSTALL" == "" ]; then
  TEST=false
fi

# From here onward: be root
if [ $UID -ne 0 ]; then
	echo $RUN_AS_ROOT 
	exit 1
fi

###file locking
echo $(eval_gettext "creating lock ...") | tee -a $LOG

# if running in a chroot, /run/lock doesn't exist. so make it
if [ ! -d "/run/lock" ];then
	mkdir -p /run/lock
fi

trap clean_up EXIT
do_flock 

# Log file for traceback
MAX_SIZE_KB=5120
LOG_SIZE_KB=0
LOG=/var/log/ddm.log
LOG2=/var/log/ddm.log.1

if [ -f $LOG ]; then
  LOG_SIZE_KB=$(ls -s $LOG | awk '{print $1}')
  if [ $LOG_SIZE_KB -gt $MAX_SIZE_KB ]; then
    mv -f $LOG $LOG2
  fi
fi 

#log version & parameters used to launch
echo "===================================" | tee -a $LOG
echo "ddm-mx: $VERSION" | tee -a $LOG
echo "kernel release: $(uname -r)" | tee -a $LOG
echo "kernel version: $(uname -v)" | tee -a $LOG
echo "command parameters: $@" |tee -a $LOG
echo "===================================" | tee -a $LOG


# =========================================================================
# =========================================================================
# =========================================================================
####removed certain options for mx
# Loop through drivers to purge
for DRV in $PURGE; do
  # Start the log
  echo "===================================" | tee -a $LOG
 #apt purge of drivers specified
  echo $(eval_gettext "Purge drivers for: ")$DRV | tee -a $LOG
 #times stamp.  starting at this day and time
  echo $(eval_gettext "Start at (m/d/y):") $(date +"%m/%d/%Y %H:%M:%S") | tee -a $LOG
  echo "===================================" | tee -a $LOG
  
  case $DRV in
    nvidia)
      install_open
      ;;
    *)#unknown option
      echo $(eval_gettext 'ERROR: Unknown argument: $DRV') | tee -a $LOG
      echo
      usage
      exit 2
      ;;
  esac
done
####removed certain options for mx
# Loop through drivers to install

for DRV in $INSTALL; do
  # Start the log
  echo "===================================" | tee -a $LOG
  echo $INSTALL_DRIVERS_FOR $DRV | tee -a $LOG
  echo $(eval_gettext "Start at (m/d/y):") $(date +"%m/%d/%Y %H:%M:%S") | tee -a $LOG
  echo "===================================" | tee -a $LOG
#  echo ""
  purge_message
  
  case $DRV in
    
    nvidia)
	  # make sure nvidia card exists
      check_for_nvidia_card
    
      # Install the Nvidia drivers
      install_nvidia
      ;;
    open)
      # Install the open drivers
      install_open
      ;;
    *)
      echo $(eval_gettext "ERROR: Unknown argument: ") $DRV | tee -a $LOG
      echo
      usage
      exit 2
      ;;
  esac
done

exit 0
}

function usage() {



  echo "======================================================================"
  echo $(eval_gettext "Device Driver Manager Help:") "ddm-mx:  $VERSION"
  echo "======================================================================"
  echo $(gettext "The following options are allowed:")
  echo
  echo "-b            " $(gettext "Offer debian-backports alternative")
  echo ""
  echo "-N            " $(gettext "Offer Nvidia developer repo alternative")
  echo "              " $(gettext "Implies -f nvidia-driver")
  echo ""
  echo "-c            " $(gettext "Create 20-nvidia.conf")
  echo ""
  echo "-g            " $(gettext "Add grub commandline and modules options to help with wayland")
  echo ""
  echo "-r            " $(gettext "Remove grub commandline and modules options related to wayland")
  echo ""
  echo "-i [driver]   " $(gettext "Install given driver.")
  echo "              " $(gettext "drivers: nvidia, open, fixbumblebee")
  echo
  echo "-p [driver]   " $(gettext "Purge given driver.")
  echo "              " $(gettext "driver: nvidia")
  echo
  echo "-f [driver]   " $(gettext "force specific nvidia driver package.")
  echo "               nvidia-driver, nvidia-legacy-390xx-driver, nvidia-tesla-418-driver,"
  echo "               nvidia-tesla-450-driver, nvidia-tesla-460-driver, nvidia-tesla-470-driver"
  echo "               nvidia-tesla-510-driver nvidia-tesla-535-driver, nvidia-legacy-340xx-driver, bumblebee-nvidia"
  echo
  echo "-t            " $(gettext "For development testing only!  simulate installs")
  echo "              " $(gettext "This will install drivers for pre-defined hardware.")
  echo "              " $(gettext "Use with -i.")
  echo
  echo "----------------------------------------------------------------------"
   echo "sudo ddm-mx -i nvidia"
  echo "======================================================================"
  exit 0
}



# =========================================================================
# =============================== Functions ===============================
# =========================================================================

# nvidia -------------------------------------------------------------------------

function preseed_nvidia {
	if $TEST  ; then
		return
	fi
  echo "Preseed"
  CANDIDATE=$1
  echo 'nvidia-support nvidia-support/check-xorg-conf-on-removal boolean false' | debconf-set-selections
  echo 'nvidia-support nvidia-support/check-running-module-version boolean true' | debconf-set-selections
  echo 'nvidia-installer-cleanup nvidia-installer-cleanup/delete-nvidia-installer boolean true' | debconf-set-selections
  echo 'nvidia-installer-cleanup nvidia-installer-cleanup/remove-conflicting-libraries boolean true' | debconf-set-selections
  echo "nvidia-support nvidia-support/last-mismatching-module-version string $CANDIDATE" | debconf-set-selections
  echo 'nvidia-support nvidia-support/needs-xorg-conf-to-enable note ' | debconf-set-selections
  echo 'nvidia-support nvidia-support/create-nvidia-conf boolean true' | debconf-set-selections
  echo 'nvidia-installer-cleanup nvidia-installer-cleanup/uninstall-nvidia-installer boolean true' | debconf-set-selections
}

function install_nvidia {
  update_sources
  install_nvidia_detect
  USER=$(logname)
  ARCHITECTURE=$(uname -m)
  if [ -z "$FORCEDRIVER" ]; then
    $NVIDIA_DETECT_MX $PCIID
    nvidia_detect_exit_code=$?
	DRIVER=$($NVIDIA_DETECT_MX $PCIID | tee -a $LOG |grep INSTALL: |tr -d ' ' |cut -d ':' -f2)
  fi
  
  UNSUPPORTED_LEGACY=""
  if [ -z "$DRIVER" ]; then
   UNSUPPORTED_LEGACY=$($NVIDIA_DETECT_MX $PCIID| grep -e173.14 -e96.43 -e71.86 -e304 -e340)
  fi
  
  # Testing
  if $TEST; then
    if [ -z "$PCIID" ]; then 
		DRIVER="nvidia-driver"
	fi
    TESTSWITCH="-s"
  fi
  
  if [ -n "$FORCEDRIVER" ]; then
		DRIVER="$FORCEDRIVER"
  fi	
  
  # Testing
  if $TEST; then
    echo "test for $DRIVER"
  fi
  
  if [[ $nvidia_detect_exit_code -eq 3 ]]; then
  	nvidia_driver_override
  fi
  	
  check_source_install
  check_cand
  
if [ "$BUMBLEBEE_NVIDIA_VERSION" = "nvidia-legacy-340xx-driver" ] ; then   
#error message about when bumblebee drivers can be used
		echo $(eval_gettext "Unsupported configuration.  bumblebee only works with 390xx drivers and up.") |tee $LOG
		my_exit
fi

  MAIN_CAND=$CANDIDATE
  MAIN_NVIDIA=$NVIDIA_VERSION
  if [ "$BACKPORTS_OVERRIDE" = "true" ]; then
	debian_backports_dialog
  else
	if [ "$NVIDIA_OVERRIDE" = "true" ]; then
		nvidia_repo_dialog
	fi
  fi
  
  echo ""
  
  check_cand
  
  check_optimus  
  
  check_cand

  choose_cand
  
  check_cand
  
  confirm_reinstall
  
  check_legacy
  
  #installed hardware requires this driver
  echo $(eval_gettext "Need driver: ")$DRIVER "$CANDIDATE" $BUMBLEBEE_NVIDIA_VERSION "$NVIDIA_VERSION" | tee -a $LOG

  set_packages 
  
  #we are going to install this package 
  echo $(eval_gettext "NVIDIA packages to install are ") $DRIVER | tee -a $LOG

#keep going
  YES_no $(eval_gettext "Continue?")
    if [ ! "$?" = "0" ]; then 
		clean_up
        exit 0
    fi
 
  # Preseed debconf answers
  preseed_nvidia $CANDIDATE
  INSTALL_RECOMMENDS="--install-recommends"
  if [ -n "$BUMBLEBEE_NVIDIA_VERSION" ]; then
    if [ "$BUMBLEBEE_NVIDIA_VERSION" != "nvidia-driver" ]; then
        INSTALL_RECOMMENDS=""
    fi 
  fi
  
  ##disable installation of nvidia-persistenced
	cp /usr/share/ddm-mx/apt/nvidia* /etc/apt/preferences.d

  
  # Install the packages
  echo "Frontend: $(echo $DEBIAN_FRONTEND)" | tee -a $LOG

  #the nvidia install command will be presented here for the log
  echo $(eval_gettext "Nvidia command ") "= apt-get install --install-recommends --reinstall -y $FORCE $SWITCH $BP $DRIVER" | tee -a $LOG
  apt-get install --reinstall -y linux-headers-$(uname -r) build-essential $TESTSWITCH 2>&1 | tee -a $LOG
  
  #install matching libxnvctrl0 for developer repo drivers
  if [ "$NVIDIA_OVERRIDE" = "true" ]; then
	apt-get install  libxnvctrl0=$CANDIDATE --allow-downgrades -y $TESTSWITCH
  fi
  
  apt-get install --reinstall $INSTALL_RECOMMENDS -y $SWITCH $BP $DRIVER $TESTSWITCH 2>&1 | tee -a $LOG
  if [ "$?" = "0" ]; then
  	POSTINSTALL=true;
  fi
  
  #install certain 32 bit libs that don't like --install-recommends
  #if [ -n "$LIB32" ]; then
	#apt-get install --reinstall -y $SWITCH $BP $TESTSWITCH $LIB32 2>&1 | tee -a $LOG  
  #fi

# Configure
  if [[ "$DRIVER" =~ "bumblebee-nvidia" ]]; then
    if [ "$USER" != "" ] && [ "$USER" != "root" ]; then
      groupadd bumblebee
      groupadd video
      usermod -a -G bumblebee,video $USER
      service bumblebeed restart
      # Adapt nvidia settings
      if [ -f /usr/lib/nvidia/current/nvidia-settings.desktop ]; then
        sed -i 's/Exec=nvidia-settings/Exec=optirun -b none nvidia-settings -c :8/' /usr/lib/nvidia/current/nvidia-settings.desktop
      fi
      # purge nvidia-xconfig and move xorg.conf away
      apt-get purge -y $FORCE nvidia-xconfig $TESTSWITCH 2>&1 | tee -a $LOG
      #mv -f /etc/X11/xorg.conf /etc/X11/xorg.conf.ddm 2>&1 | tee -a $LOG
    else
      echo $(eval_gettext "ERROR: Could not configure Bumblebee for user: ") $USER | tee -a $LOG
    fi
  else
    if $TEST; then
    echo $(eval_gettext "test enabled, not creating xorg.conf file")
    #nvidia-xconfig | tee -a $LOG
    else
        if [ "$NVIDIA_XCONFIG" = "nvidia-xconfig" ]; then
            echo $(eval_gettext "creating /etc/X11/xorg.conf file")
            nvidia-xconfig | tee -a $LOG
        fi
        #340 nvidia fixes
        if [ "$DRIVER_ORIGINAL" == "nvidia-legacy-340xx-driver" ] || [ "$BUMBLEBEE_NVIDIA_VERSION" == "nvidia-legacy-340xx-driver" ]; then
        nvidia-340-fix
        fi
    fi
  fi
  #POSTINSTALL
  if [ $POSTINSTALL ]; then
    echo "POSTINSTALL" | tee -a $LOG
  	#add possible missing symlinks
  	#commented out, doesn't seem to be necessary
  	#create_modprobe_symlinks
 	
  	#create 20_nvidia.conf file for non-optimus parts
    # also create grub config changes
  	if [ $OPTIMUS -eq 1 ]; then
  	    #for 340xx legacy drivers, force creation of 20-nvidia.conf
  	    if [ "$DRIVER_ORIGINAL" == "nvidia-legacy-340xx-driver" ]; then 
  			create_20_nvidiaconf
  		fi
        #add grub and module options
        if [ "$DRIVER_ORIGINAL" != "nvidia-legacy-340xx-driver" ]; then
  	        add_nvidia_module_config
  	    fi
  	fi
  	#backup any existing xorg.conf file
  	if [ -e /etc/X11/xorg.conf ]; then
  		XORGBACKUP="/etc/X11/xorg.conf.bak.$(date +%Y%m%H%M%S)"
  		echo "mv /etc/X11/xorg.conf --> $XORGBACKUP" | tee -a $LOG
  		mv /etc/X11/xorg.conf $XORGBACKUP
  	fi
  	#update initramfs one more time
  	  	update_initramfs
  fi
  echo $(eval_gettext "Finished") | tee -a $LOG
  echo ""
  finish_purge_message
  
}

# open -------------------------------------------------------------------------

function purge_proprietary_drivers {
  rm /etc/X11/xorg.conf 2>/dev/null
  rm /etc/modprobe.d/nvidia* 2>/dev/null
  rm /etc/modprobe.d/blacklist-nouveau.conf 2>/dev/null
  #reset libxnvctrl0 to debian version 
  apt-get install libxnvctrl0=$(apt-cache madison libxnvctrl0 | awk '{print $3}') --allow-downgrades -y $TESTSWITCH
  remove_20_nvidiaconf
  # Leave nvidia-installer-cleanup
  apt-get purge $FORCE $(apt-cache pkgnames | grep nvidia |grep -v firmware | grep -v cleanup | cut -d':' -f1) bumblebee* primus* primus*:i386 *nvidia*:i386 $TESTSWITCH 2>&1 | tee -a $LOG
  # apt-get purge $FORCE bumblebee* primus* primus*:i386 2>&1 | tee -a $LOG
  # remove possible leftover symlinks
	remove_modprobe_symlinks
  # remove module options and grub config
  remove_nvidia_module_config
  
  if [ "$?" = "0" ]; then 
      #success in removing proprietary drivers and returning to open source drivers
      echo $(eval_gettext "Proprietary drivers removed") | tee -a $LOG
  fi
}

function install_open {
  # Make sure you have the most used drivers installed 
  # These are installed by default on MX
  nvidia-340-reverse-fix
  DRIVER="xserver-xorg-video-nouveau xserver-xorg-video-vesa xserver-xorg-video-intel xserver-xorg-video-fbdev xserver-xorg-video-radeon xserver-xorg-video-ati xserver-xorg-video-nouveau"
  
  # Install the packages
  update_sources
  echo "Frontend: $(echo $DEBIAN_FRONTEND)" | tee -a $LOG
  #the command to restore open source drivers presented for the log
  echo $(eval_gettext "Open command ") "= apt-get install --reinstall -y $FORCE $DRIVER" | tee -a $LOG
  apt-get install --reinstall $FORCE $DRIVER $TESTSWITCH 2>&1 | tee -a $LOG
  
  if [ "$?" = "0" ]; then 
      #success at installing open source drivers
      echo $(eval_gettext "Open drivers installed") | tee -a $LOG
  fi
  
  # Now cleanup
  purge_proprietary_drivers
}

clean_up()
{
unflock $LOCK_FILE
echo "" | tee -a $LOG 
echo "" | tee -a $LOG 

if [ -f /etc/apt/preferences.d/ddm-version-temp ]; then
	rm /etc/apt/preferences.d/ddm-version-temp
fi
if [ -f /etc/apt/sources.list.d/debian-backports-temp.list ]; then
  rm -f /etc/apt/sources.list.d/debian-backports-temp.list
  #return sources to a state before this application made any changes
  echo $(eval_gettext "Resetting sources")
  apt-get update
  echo ""
fi
if [ -f /etc/apt/sources.list.d/mx-test-repo-temp.list ]; then
    rm -f /etc/apt/sources.list.d/mx-test-repo-temp.list
    echo $(eval_gettext "Resetting sources")
    apt-get update
    echo ""
fi
if [ -f /etc/apt/sources.list.d/nvidia-repo-temp.list ]; then
    rm -f /etc/apt/sources.list.d/nvidia-repo-temp.list
    echo $(eval_gettext "Resetting sources")
    apt-get update
    echo ""
fi
#only cleanup nvidia sources if the -N switch was used
if [ "$NVIDIA_OVERRIDE" = "true" ]; then
  if [ -f /etc/apt/sources.list.d/cuda-debian$DEBIAN_VERSION_NUMBER-x86_64.list ]; then
    echo $(eval_gettext "Resetting sources")
    apt purge cuda-keyring -y
    rm -f /etc/apt/sources.list.d/cuda-debian$DEBIAN_VERSION_NUMBER-x86_64.list
    apt-get update
    echo ""
  else
   #check fallback location
   if [ -f /etc/apt/sources.list.d/cuda-debian12-x86_64.list ]; then
  	 echo $(eval_gettext "Resetting sources")
   	 apt purge cuda-keyring -y
   	 rm -f /etc/apt/sources.list.d/cuda-debian12-x86_64.list
   	 apt-get update
   	 echo ""
   fi
   fi
fi

##re-enable nvidia-peristenced availability

if [ -e "/etc/apt/preferences.d/nvidia-ddm-temp" ]; then 
	rm /etc/apt/preferences.d/nvidia-ddm-temp*
fi

echo -n $(eval_gettext "Press <Enter> to exit") | tee -a $LOG 
read x
}

my_exit() {
    local ret=${1:-0}

    # Msg "=> cleaning up"
    exit $ret
}

enable_debian_backports()
{
#enabling debian-backports
  echo $(eval_gettext "Enabling backports repo")
  echo $(eval_gettext "Running apt-get update...")
  echo "$BP_REPO_ADDRESS $BP main contrib non-free">>/etc/apt/sources.list.d/debian-backports-temp.list
  update_sources
  echo ""
  if [ "$ARCH" = "amd64" ]; then
    #inform we are updating nvidia-detect package
    echo $(eval_gettext "Installing latest nvidia-detect package")|tee -a $LOG
    echo ""
    apt-get install $SWITCH $BP nvidia-detect |tee -a $LOG  
    echo ""
  fi
}

enable_mx_test_repo()
{
#enabling mx_test_repo
  echo $(eval_gettext "Enabling MX Test repo")
  echo $(eval_gettext "Running apt-get update...")
  echo "$MX_TEST_REPO_ADDRESS">>/etc/apt/sources.list.d/mx-test-repo-temp.list
  update_sources
  echo ""
  if [ "$ARCH" = "amd64" ]; then
    echo $(eval_gettext "Installing latest nvidia-detect package")|tee -a $LOG
    echo ""
    apt-get install $SWITCH "$BP" nvidia-detect |tee -a $LOG  
    echo ""
  fi
}

enable_nvidia_repo()
{
#enabling nvidia-direct repo
  echo $(eval_gettext "Enabling Nvidia developer repo")
  #getting the nvidia gpg archive key
  echo $(eval_gettext "Getting Nvidia repo signing key")
  NVIDIA_KEY_ADDRESS="https://developer.download.nvidia.com/compute/cuda/repos/debian$DEBIAN_VERSION_NUMBER/x86_64/cuda-keyring_1.1-1_all.deb"
  echo $NVIDIA_KEY_ADDRESS
  wget $NVIDIA_KEY_ADDRESS -O /tmp/nvidia-keyring.deb
  if [ $? -ne 0 ]; then
  	#try debian 12 version as a fallback
  	echo $(eval_gettext "Debian 13 repo not found, falling back to Debian 12 repository") 	
  	DEBIAN_VERSION_NUMBER="12"
  	echo $(eval_gettext "Getting Nvidia repo signing key")
  NVIDIA_KEY_ADDRESS="https://developer.download.nvidia.com/compute/cuda/repos/debian$DEBIAN_VERSION_NUMBER/x86_64/cuda-keyring_1.1-1_all.deb"
  echo $NVIDIA_KEY_ADDRESS
  wget $NVIDIA_KEY_ADDRESS -O /tmp/nvidia-keyring.deb
  fi
  dpkg -i /tmp/nvidia-keyring.deb
  rm /tmp/nvidia-keyring.deb
  if [ $? = 0 ]; then
       echo ""
  else
  	   #problem downloading and installing the nvidia gpg key package
       echo $(eval_gettext "Error downloading nvidia direct repo key")
       return
  fi

  update_sources
  echo ""
 #don't install nvidia-detect with nvidia developer repo...depends causes problems with existing nvidia packages
 #if [ "$ARCH" = "amd64" ]; then
 #  echo $(eval_gettext "Installing latest nvidia-detect package")|tee -a $LOG
 #  echo ""
 #  apt-get install $SWITCH "$BP" nvidia-detect |tee -a $LOG  
 #
 #  echo ""
 #fi
}

debian_backports_dialog()
{
echo $(eval_gettext "Would you like to check debian-backports for a later version?") | tee -a $LOG
        echo "" | tee -a $LOG
        echo $(eval_gettext "Yes or No?") | tee -a $LOG
        echo "" | tee -a $LOG
        echo 1: $(eval_gettext "Yes") | tee -a $LOG
        echo 2: $(eval_gettext "No") | tee -a $LOG
        echo "" | tee -a $LOG
        echo $(eval_gettext "Enter Number of selection") | tee -a $LOG
        read -n 1 -e x

        case $x in
           1) echo $(eval_gettext "Ok")...| tee -a $LOG 
	      SWITCH="-t"
              BP=$BP_REPO
	      enable_debian_backports	;;
           2) echo $(eval_gettext "Ok")... | tee -a $LOG
              SWITCH=""
	      BP=""             ;;
           *) echo $(eval_gettext "invalid option.")  $(eval_gettext "exiting")... | tee -a $LOG && exit 0;;
        esac
}

mx_test_repo_dialog()
{
echo $(eval_gettext "Would you like to check MX Test Repo for a later version?") >> $LOG
yes_NO "$(eval_gettext "Would you like to check MX Test Repo for a later version?")"

        case $? in
           0)   echo $(eval_gettext "Ok")...| tee -a $LOG 
                SWITCH="-t"
                BP="a=mx,c=test"
                enable_mx_test_repo	;;
           1)   echo $(eval_gettext "Ok")... | tee -a $LOG
                SWITCH=""
                BP=""           ;;
           *) echo $(eval_gettext "invalid option.")  $(eval_gettext "exiting")... | tee -a $LOG && exit 0;;
        esac
}

nvidia_repo_dialog()
{
echo $(eval_gettext "Would you like to check the Nvidia developer repo for a later version?") >> $LOG
yes_NO "$(eval_gettext "Would you like to check the Nvidia developer repo for a later version?")"

        case $? in
           0)   echo $(eval_gettext "Ok")...| tee -a $LOG 
                SWITCH=""
                BP=""
                enable_nvidia_repo	;;
           1)   echo $(eval_gettext "Ok")... | tee -a $LOG
                SWITCH=""
                BP=""           ;;
           *) echo $(eval_gettext "invalid option.")  $(eval_gettext "exiting")... | tee -a $LOG && exit 0;;
        esac
}


which_driver()
{
#a choice of driver versions is being offerred
echo $(eval_gettext "Which driver do you wish to install") | tee -a $LOG
        echo "" | tee -a $LOG
        echo $(eval_gettext "Main repos or debian-backports?") | tee -a $LOG
        echo "" | tee -a $LOG
        echo 1: $(eval_gettext "Main") $MAIN_CAND $BUMBLEBEE_NVIDIA_VERSION $MAIN_NVIDIA| tee -a $LOG
        echo "" | tee -a $LOG
        echo 2: "debian-backports" $CANDIDATE $BUMBLEBEE_NVIDIA_VERSION $NVIDIA_VERSION| tee -a $LOG
        echo "" | tee -a $LOG
	echo 3: $(eval_gettext "Exit") | tee -a $LOG
        echo "" | tee -a $LOG
        echo $(eval_gettext "Enter Number of selection") | tee -a $LOG
        read -n 1 -e x

        case $x in
           1) echo $(eval_gettext "Ok")...| tee -a $LOG 
	      SWITCH=""
              BP=""
              NVIDIA_VERSION=$MAIN_NVIDIA
              rm /etc/apt/sources.list.d/debian-backports-temp.list
              apt-get update  
              #replace nvidia-detect from main repo
              #only install if nvidia-detect was present already (not present on 32 bit systems)
              if [ "$ARCH" = "amd64" ]; then
                #put nvidia-detect back to version in current enabled repos
              	echo $(eval_gettext "Reset nvidia-detect") | tee -a $LOG
              	apt-get remove nvidia-detect -y && apt-get install nvidia-detect -y                     
              fi
	      ;;
           2) echo $(eval_gettext "Ok")... | tee -a $LOG
                #NVIDIA_XCONFIG=""
                     ;;
           3) echo $(eval_gettext "exiting") |tee -a $LOG && exit 0;;

           *) echo $(eval_gettext "invalid option.")  $(eval_gettext "exiting")... | tee -a $LOG && exit 0;;
        esac
}

which_driver_mx()
{
echo $(eval_gettext "Which driver do you wish to install") | tee -a $LOG
        echo "" | tee -a $LOG
        echo $(eval_gettext "Main repos or MX Test") | tee -a $LOG
        echo "" | tee -a $LOG
        echo 1: $(eval_gettext "Main") $DRIVER $MAIN_CAND $BUMBLEBEE_NVIDIA_VERSION $MAIN_NVIDIA| tee -a $LOG
        echo "" | tee -a $LOG
        echo 2: $(eval_gettext "MX Test") $DRIVER $CANDIDATE $BUMBLEBEE_NVIDIA_VERSION $NVIDIA_VERSION| tee -a $LOG
        echo "" | tee -a $LOG
	echo 3: $(eval_gettext "Exit") | tee -a $LOG
        echo "" | tee -a $LOG
        echo $(eval_gettext "Enter Number of selection") | tee -a $LOG
        read -n 1 -e x

        case $x in
           1) echo $(eval_gettext "Ok")...| tee -a $LOG 
                SWITCH=""
                BP=""
                NVIDIA_VERSION=$MAIN_NVIDIA
                rm /etc/apt/sources.list.d/mx-test-repo-temp.list
                apt-get update
                #replace nvidia-detect from main repo
                #only install if nvidia-detect was present already (not present on 32 bit systems)
                if [ "$ARCH" = "amd64" ]; then
                	echo $(eval_gettext "Reset nvidia-detect") | tee -a $LOG
                	apt-get remove nvidia-detect -y && apt-get install nvidia-detect -y
                fi
                ;;
           2)   echo $(eval_gettext "Ok")... | tee -a $LOG
                SWITCH="-t"
                BP="a=mx,c=test"
                #NVIDIA_XCONFIG=""
                     ;;
           3) echo $(eval_gettext "exiting") |tee -a $LOG && exit 0;;

           *) echo $(eval_gettext "invalid option.")  $(eval_gettext "exiting")... | tee -a $LOG && exit 0;;
        esac
}

which_driver_nvidia()
{
echo $(eval_gettext "Which driver do you wish to install") | tee -a $LOG
        echo "" | tee -a $LOG
        echo $(eval_gettext "Main repos or Nvidia direct repo") | tee -a $LOG
        echo "" | tee -a $LOG
        echo 1: $(eval_gettext "Main") $DRIVER $MAIN_CAND $BUMBLEBEE_NVIDIA_VERSION $MAIN_NVIDIA| tee -a $LOG
        echo "" | tee -a $LOG
        echo 2: $(eval_gettext "Nvidia Direct") $DRIVER $CANDIDATE $BUMBLEBEE_NVIDIA_VERSION $NVIDIA_VERSION| tee -a $LOG
        echo "" | tee -a $LOG
	echo 3: $(eval_gettext "Exit") | tee -a $LOG
        echo "" | tee -a $LOG
        echo $(eval_gettext "Enter Number of selection") | tee -a $LOG
        read -n 1 -e x

        case $x in
           1) echo $(eval_gettext "Ok")...| tee -a $LOG 
                SWITCH=""
                BP=""
                NVIDIA_VERSION=$MAIN_NVIDIA
                apt purge -y cuda-keyring
                apt-get update
                #replace nvidia-detect from main repo
                #only install if nvidia-detect was present already (not present on 32 bit systems)
                if [ "$ARCH" = "amd64" ]; then
                	echo $(eval_gettext "Reset nvidia-detect") | tee -a $LOG
                	apt-get remove nvidia-detect -y && apt-get install nvidia-detect -y
                fi
                ;;
           2)   echo $(eval_gettext "Ok")... | tee -a $LOG
                ;;
                
           3) echo $(eval_gettext "exiting") |tee -a $LOG && exit 0;;

           *) echo $(eval_gettext "invalid option.")  $(eval_gettext "exiting")... | tee -a $LOG && exit 0;;
        esac
}


check_cand()
{
CANDIDATE=$(LANG=C apt-cache policy $SWITCH $BP $DRIVER | grep Candidate | awk '{print $2}' | tr -d ' ')
INSTALLED=$(env LANG=C apt-cache policy $DRIVER | grep Installed | awk '{print $2}' | tr -d ' ')

if [ "$DRIVER" = "bumblebee-nvidia" ]; then 
        NVIDIA_VERSION=$(LANG=C apt-cache policy $SWITCH $BP $BUMBLEBEE_NVIDIA_VERSION | grep Candidate | awk '{print $2}' | tr -d ' ')
        NVIDIA_INSTALLED=$(env LANG=C apt-cache policy $BUMBLEBEE_NVIDIA_VERSION | grep Installed | awk '{print $2}' | tr -d ' ')
fi

echo ""
  echo $(eval_gettext "Candidate is: ") $DRIVER $CANDIDATE $BUMBLEBEE_NVIDIA_VERSION $NVIDIA_VERSION| tee -a $LOG
  echo $(eval_gettext "Installed is: ") $DRIVER $INSTALLED $BUMBLEBEE_NVIDIA_VERSION $NVIDIA_INSTALLED | tee -a $LOG
echo ""
  
}
update_sources()
{
    local ret
    echo ""
    echo $(eval_gettext "Refreshing Sources with apt-get update") | tee -a $LOG
    YES_no $(eval_gettext "Continue?")
    if [ "$?" = "0" ]; then 
        apt-get update
        if [ "$?" != "0" ]; then
            echo ""
            echo ""
            echo $(eval_gettext 'There was a problem with the apt-get update.  See $LOG for details') | tee -a $LOG
            echo ""
            echo ""
			my_exit
        fi
    fi
}

purge_message()
{
#provide user with information on going back to open source drivers
local PURGE_MESSAGE=$(eval_gettext "To restore open source drivers use:  ")
echo ""| tee -a $LOG
echo "========================================"| tee -a $LOG
echo "========================================"| tee -a $LOG
echo ""| tee -a $LOG
echo "$PURGE_MESSAGE"  | tee -a $LOG
echo "sudo ddm-mx -p nvidia"| tee -a $LOG
echo ""| tee -a $LOG
echo "========================================"| tee -a $LOG
echo "========================================"| tee -a $LOG
echo ""| tee -a $LOG
}

finish_purge_message()
{
local USER="$(logname)"
local USER_HOME_PATH="/home/$USER/ddm-mx-nvidia_removal_command.txt"
local PURGE_MESSAGE=$(eval_gettext "To restore open source drivers later use:  ") 
echo ""| tee "$USER_HOME_PATH"
echo "========================================"| tee -a "$USER_HOME_PATH"
echo "========================================"| tee -a "$USER_HOME_PATH"
echo ""| tee -a "$USER_HOME_PATH"
echo "$PURGE_MESSAGE"  | tee -a "$USER_HOME_PATH"
echo "sudo ddm-mx -p nvidia"| tee -a "$USER_HOME_PATH"
echo ""| tee -a $USER_HOME_PATH
echo "========================================"| tee -a "$USER_HOME_PATH"
echo "========================================"| tee -a "$USER_HOME_PATH"
echo ""| tee -a "$USER_HOME_PATH"
echo ""| tee -a "$USER_HOME_PATH"
#provide user with information on where file with recovery command is stored
echo $(eval_gettext "For recovery help see ") | tee -a "$USER_HOME_PATH"
echo "https://mxlinux.org/wiki/hardware/nvidia-driver-install-recovery" | tee -a "$USER_HOME_PATH"
echo ""
#provide user with information on where file with recovery command is stored
echo $(eval_gettext "Information written to ")"$USER_HOME_PATH"
chown $USER:$USER "$USER_HOME_PATH"

}

nvidia-340-fix()
{
if $TEST  ; then
	return
fi
# backup libglx.so
local lib_version
lib_version=$(LANG=C apt-cache policy nvidia-legacy-340xx-driver |grep Candidate |cut -d: -f2|cut -d. -f2|cut -d- -f1)
if [ -f /usr/lib/nvidia/legacy-340xx/libglx.so.340.$lib_version ]; then
	if [ -f /usr/lib/xorg/modules/extensions/libglx.so ]; then
	    echo "mv /usr/lib/xorg/modules/extensions/libglx.so /usr/lib/xorg/modules/extensions/libglx.so.bak" | tee -a $LOG
		mv /usr/lib/xorg/modules/extensions/libglx.so /usr/lib/xorg/modules/extensions/libglx.so.bak | tee -a $LOG
		echo "ln -s /usr/lib/nvidia/legacy-340xx/libglx.so.340.$lib_version /usr/lib/xorg/modules/extensions/libglx.so" | tee -a $LOG
		ln -s /usr/lib/nvidia/legacy-340xx/libglx.so.340.$lib_version /usr/lib/xorg/modules/extensions/libglx.so | tee -a $LOG
	fi
fi
}

nvidia-340-reverse-fix()
{
if $TEST ; then
	return
fi
	# if backup libglx.so exists, then revert it back.  this will take place just before reinstallation of the open drivers.
if [ -L /usr/lib/xorg/modules/extensions/libglx.so ]; then
	if [ -f /usr/lib/xorg/modules/extensions/libglx.so.bak ]; then
	    echo "remove symlink libglx.so"
		rm /usr/lib/xorg/modules/extensions/libglx.so | tee -a $LOG
		echo "restore original libglx.so"
		mv /usr/lib/xorg/modules/extensions/libglx.so.bak /usr/lib/xorg/modules/extensions/libglx.so | tee -a $LOG
	fi
fi
}

check_source_install(){
	#check for possible source install
  if [ -e /usr/bin/nvidia-installer ]; then
    #found an installation from source
    echo $(eval_gettext "Possible previous install from source or smxi/sgfxi detected.") | tee -a $LOG
    echo $(eval_gettext "Version detected: ") $(modinfo nvidia | grep ^version: | sed 's/[^0-9.]*//g') | tee -a $LOG
    echo $(eval_gettext "Latest possible with this script : ") $CANDIDATE | tee -a $LOG
    #please remove the source installation if you wish to use ddm-mx
    echo $(eval_gettext "Please remove with  <sudo nvidia-install --uninstall> and reboot if you wish to proceed") | tee -a $LOG
	exit 10
  fi
  # check possible generic install
  if [ -e /usr/bin/nvidia-modprobe ]; then
	#found installation from any source
	echo "========================================"| tee -a $LOG
	echo $(eval_gettext "Possible previous install detected.") | tee -a $LOG
	echo "========================================"| tee -a $LOG
#	purge_message
#	exit 10
  fi
  
}

# Check for Optimus
check_optimus(){
    local MIN_XORG_VERSION MIN_NVIDIA_VERSION MAJOR_NVIDIA_VERSION
    local YELLOW="\033[1;33m" local NC="\033[0m" # No Color
    OPTIMUS=1
	if lspci -vnn | grep Intel |grep -q 0300 ; then
		if lspci -vnn | grep NVIDIA | grep -q 0302 ; then
		    #possible hybrid graphics detected
			echo $(eval_gettext "nvidia-optimus detected") | tee -a $LOG
			OPTIMUS=2
		else
		    #ask if this system has hybrid graphics
            echo -e "${YELLOW}$(eval_gettext "Answer the next question NO if you are using your Optimus Nvidia card in discrete mode")${NC}"
			YES_no "$(eval_gettext "Is this a NVIDIA/INTEL Optimus system?")"
			if [ "$?" = "0" ]; then
				OPTIMUS=2
			fi
		
		fi
	fi

	
	if [ -z $CANDIDATE ]; then
		return
	fi

    if [ "$OPTIMUS" -eq 2 ]; then
        # Bumblebee used to be required, but now NVIDIA drivers support Optimus out of the box.
        # See https://wiki.debian.org/NVIDIA%20Optimus#Using_NVIDIA_PRIME_Render_Offload
        
        # Requires Xorg 1.20.8 and NVIDIA 450 or greater
        MIN_XORG_VERSION="12008000"
        MIN_NVIDIA_VERSION="450"

        # I'm sure there's a cleaner way to detect Xorg version, but this works for now.
        XORG_VERSION=`LANG=C xdpyinfo | grep "vendor release" | grep -Poe '\:\s(.*)' | cut -c 3-`
        if [ test ]; then
			echo "$XORG_VERSION"
		fi

        # Get major version of NVIDIA 
        MAJOR_NVIDIA_VERSION=`echo $CANDIDATE | cut -d. -f1`
        
        if [ test ]; then
			echo "xorg version" "$XORG_VERSION"
			echo "nvidia major version" "$MAJOR_NVIDIA_VERSION"
		fi

        if { echo $MIN_XORG_VERSION; echo $XORG_VERSION; } | sort -n -c 2>/dev/null
        then
           if [ "$MAJOR_NVIDIA_VERSION" -ge "$MIN_NVIDIA_VERSION" ]
           then
				echo ""
                echo $(eval_gettext "You can use the new PRIMUS driver built in to the nvidia drivers.") | tee -a $LOG
                echo $(eval_gettext 'Use "nvidia-run-mx" followed by your application command to use the nvidia graphics') | tee -a $LOG
                echo ""
                printf "$(eval_gettext "If you want to force the older bumblebee optimus drivers,\n quit and restart with sudo ddm-mx -i nvidia -f bumblebee-nvidia")" | tee -a $LOG
                echo ""    
            else
                echo $(eval_gettext "You need to use the bumblebee-nvidia driver.") | tee -a $LOG
                # For nvidia-driver versions below 450 we must still use Bumblebee
                BUMBLEBEE_NVIDIA_VERSION="$DRIVER"
                DRIVER='bumblebee-nvidia'
            fi
        else
            echo $(eval_gettext "You need to use the bumblebee-nvidia driver.") | tee -a $LOG
            # For xorg versions below 1.20.8 we must still use Bumblebee
            BUMBLEBEE_NVIDIA_VERSION="$DRIVER"
            DRIVER='bumblebee-nvidia'
        fi
    fi
}

check_legacy(){
	if [ "$DRIVER" == "" ] || [ "$CANDIDATE" == "" ]; then
      if [ "$UNSUPPORTED_LEGACY" == "" ]
         then
			  echo ""
              echo $(eval_gettext "nvidia driver not available, check your repo sources") | tee -a $LOG
              exit 3
 
         else 
          echo ""
	      echo $(eval_gettext "Uh oh. Your card is only supported by older legacy drivers which are not in any current Debian suite.") | tee -a $LOG
              exit 7
      fi
  fi
}

set_packages(){
	  # Add additional packages
  
  DRIVER_ORIGINAL=$DRIVER

  case $DRIVER in 
                     nvidia-driver)    if [ "$ARCHITECTURE" == "x86_64" ]; then
                                           NVIDIA_XCONFIG=""
                                           DRIVER="$DRIVER nvidia-settings nvidia-kernel-dkms libnvidia-encode1" 
                                       else
										   NVIDIA_XCONFIG=""
                                           DRIVER="$DRIVER nvidia-kernel-dkms nvidia-settings libnvidia-encode1" 
                                       fi
                                       ;;
        nvidia-legacy-390xx-driver)    if [ "$ARCHITECTURE" == "x86_64" ]; then
                                           NVIDIA_XCONFIG=""
                                           DRIVER="$DRIVER nvidia-settings-legacy-390xx nvidia-legacy-390xx-kernel-dkms"
                                       else
                                           NVIDIA_XCONFIG=""
                                           DRIVER="$DRIVER nvidia-settings-legacy-390xx nvidia-legacy-390xx-kernel-dkms"
                                       fi
                                       ;;
         nvidia-legacy-340xx-driver)    if [ "$ARCHITECTURE" == "x86_64" ]; then
                                           NVIDIA_XCONFIG=""
                                           DRIVER="$DRIVER nvidia-legacy-340xx-kernel-dkms"
                                       else
                                           NVIDIA_XCONFIG=""
                                           DRIVER="$DRIVER nvidia-legacy-340xx-kernel-dkms"
                                       fi
                                       ;;
        nvidia-tesla-418-driver)    if [ "$ARCHITECTURE" == "x86_64" ]; then
                                           NVIDIA_XCONFIG=""
                                           DRIVER="$DRIVER nvidia-settings-tesla-418 nvidia-tesla-418-kernel-dkms"
                                       else
                                           NVIDIA_XCONFIG=""
                                           DRIVER="$DRIVER nvidia-settings-tesla-418 nvidia-tesla-418-kernel-dkms"
                                       fi
                                       ;;
        nvidia-tesla-450-driver)    if [ "$ARCHITECTURE" == "x86_64" ]; then
                                           NVIDIA_XCONFIG=""
                                           DRIVER="$DRIVER nvidia-settings-tesla-450 nvidia-tesla-450-kernel-dkms"
                                       else
                                           NVIDIA_XCONFIG=""
                                           DRIVER="$DRIVER nvidia-settings-tesla-450 nvidia-tesla-450-kernel-dkms"
                                       fi
                                       ;;
        nvidia-tesla-460-driver)    if [ "$ARCHITECTURE" == "x86_64" ]; then
                                           NVIDIA_XCONFIG=""
                                           DRIVER="$DRIVER nvidia-settings-tesla-460 nvidia-tesla-460-kernel-dkms"
                                       else
                                           NVIDIA_XCONFIG=""
                                           DRIVER="$DRIVER nvidia-settings-tesla-460 nvidia-tesla-460-kernel-dkms"
                                       fi
                                       ;;
        nvidia-tesla-470-driver)    if [ "$ARCHITECTURE" == "x86_64" ]; then
                                           NVIDIA_XCONFIG=""
                                           DRIVER="$DRIVER nvidia-settings-tesla-470 nvidia-tesla-470-kernel-dkms"
                                       else
                                           NVIDIA_XCONFIG=""
                                           DRIVER="$DRIVER nvidia-settings-tesla-470 nvidia-tesla-470-kernel-dkms"
                                       fi
                                       ;;
                                       
        nvidia-tesla-510-driver)    if [ "$ARCHITECTURE" == "x86_64" ]; then
                                           NVIDIA_XCONFIG=""
                                           DRIVER="$DRIVER nvidia-settings-tesla-510 nvidia-tesla-510-kernel-dkms"
                                       else
                                           NVIDIA_XCONFIG=""
                                           DRIVER="$DRIVER nvidia-settings-tesla-510 nvidia-tesla-510-kernel-dkms"
                                       fi
                                       ;;
        nvidia-tesla-535-driver)    if [ "$ARCHITECTURE" == "x86_64" ]; then
                                           NVIDIA_XCONFIG=""
                                           DRIVER="$DRIVER nvidia-settings-tesla-535 nvidia-tesla-535-kernel-dkms"
                                       else
                                           NVIDIA_XCONFIG=""
                                           DRIVER="$DRIVER nvidia-settings-tesla-535 nvidia-tesla-535-kernel-dkms"
                                       fi
                                       ;;
                  bumblebee-nvidia)    if [ "$DRIVER" == "bumblebee-nvidia" ]; then
											NVIDIA_XCONFIG=""
											
                                       # Bumblebee drivers
                                            if [ "$BUMBLEBEE_NVIDIA_VERSION" == "nvidia-legacy-390xx-driver" ]; then
												DRIVER="$DRIVER $BUMBLEBEE_NVIDIA_VERSION nvidia-settings-legacy-390xx nvidia-legacy-390xx-kernel-dkms $BUMBLEBEE_EXTRA_LIBS"
											fi
											if [ "$BUMBLEBEE_NVIDIA_VERSION" == "nvidia-driver" ]; then
												DRIVER="$DRIVER $BUMBLEBEE_NVIDIA_VERSION nvidia-settings nvidia-kernel-dkms $BUMBLEBEE_EXTRA_LIBS"
											fi
											
                                       fi
                                       ;;
                                 *)
                                       echo "2" $(eval_gettext "ERROR: Unknown argument: ") $DRV | tee -a $LOG 
                                       echo | tee -a $LOG 
                                       usage
                                       exit 2
   esac
   
}

choose_cand(){
	if [ -f /etc/apt/sources.list.d/debian-backports-temp.list ]; then
	   #candidate from enabled repos
       echo $(eval_gettext "Main repo candidate is:  ") $MAIN_CAND |tee -a $LOG
       #candidate from debian backports repo
       echo $(eval_gettext "Debian backports candidate is:  ")  $CANDIDATE |tee -a $LOG
       #installed version, if any
       echo $(eval_gettext "Installed is: ") $INSTALLED | tee -a $LOG
       echo ""
       which_driver
       echo ""
  fi  
  
  if [ -f /etc/apt/sources.list.d/mx-test-repo-temp.list ]; then
       echo $(eval_gettext "Main repo candidate is:  ") $MAIN_CAND |tee -a $LOG
       #test repo candidate
       echo $(eval_gettext "MX Test repo candidate is:  ")  $CANDIDATE |tee -a $LOG
       echo $(eval_gettext "Installed is: ") $INSTALLED | tee -a $LOG
       echo ""
       which_driver_mx
       echo ""
  fi  
  if [ -f /etc/apt/sources.list.d/cuda-debian$DEBIAN_VERSION_NUMBER-x86_64.list ]; then
       echo $(eval_gettext "Main repo candidate is:  ") $MAIN_CAND |tee -a $LOG
       #Nvidia developer repo candidate here
       echo $(eval_gettext "Nvidia developer repo candidate is:  ")  $CANDIDATE |tee -a $LOG
       echo $(eval_gettext "Installed is: ") $INSTALLED | tee -a $LOG
       echo ""
       choose_version_nvidia
       echo ""
  fi 
}

confirm_reinstall(){
	if [ "$CANDIDATE" != "" ]; then
      if [ "$INSTALLED" = "$CANDIDATE" ]; then
        echo $(eval_gettext "nvidia driver already installed") | tee -a $LOG
        echo "" | tee -a $LOG
        echo $(eval_gettext "Reinstall or quit?") | tee -a $LOG
        echo "$NVIDIA packages to install are " $DRIVER | tee -a $LOG
        echo "" | tee -a $LOG
        echo 1: $(eval_gettext "Reinstall") | tee -a $LOG
        echo 2: $(eval_gettext "quit") | tee -a $LOG
        echo "" | tee -a $LOG
        echo $(eval_gettext "Enter Number of selection") | tee -a $LOG
        read -n 1 -e x

        case $x in
           1) echo $(eval_gettext "reinstalling")... | tee -a $LOG ;;
           2) echo $(eval_gettext "exiting")... | tee -a $LOG && exit 0 ;;
           *) echo $(eval_gettext "invalid option.")  $(eval_gettext "exiting")... | tee -a $LOG && exit 0;;
        esac
      fi
      echo ""
  fi
}

check_for_nvidia_card(){
	# Bumblebee: https://wiki.debian.org/Bumblebee
      # Get device ids for Nvidia
      local BCID DEVICEIDS
      BCID='10de'
      DEVICEIDS=$(lspci -n -d $BCID: | awk '{print $3}' | cut -d':' -f2)
      
      # Testing
      if $TEST; then
        DEVICEIDS='0a74'
      fi

    if [ -z "$FORCEDRIVER" ]; then
		if [ "$DEVICEIDS" == "" ]; then
			echo $(eval_gettext "No nvidia card found - exiting") | tee -a $LOG
			exit 8
		fi
    fi
}

install_nvidia_detect(){
if [ "$ARCH" = "amd64" ]; then
	if [ ! -x "/usr/bin/nvidia-detect" ]; then
		echo $(eval_gettext "Installing latest nvidia-detect package")|tee -a $LOG
		echo ""
		apt-get install $SWITCH $BP nvidia-detect $TESTSWITCH |tee -a $LOG  
		echo ""
    fi
fi
}

create_modprobe_symlinks(){
	#files to check for
	#/etc/modprobe.d/nvidia-blacklists-nouveau.conf
    #/etc/modprobe.d/nvidia-modprobe.conf
    #/etc/modprobe.d/nvidia-options.conf
    if $TEST; then
		return
	fi
	echo "symlinks" | tee -a $LOG
    
    if [ ! -e /etc/modprobe.d/nvidia-blacklists-nouveau.conf ]; then
		ln -s /etc/nvidia/current/nvidia-blacklists-nouveau.conf /etc/modprobe.d/nvidia-blacklists-nouveau.conf
	fi
	if [ ! -e /etc/modprobe.d/nvidia-modprobe.conf ]; then
		ln -s /etc/nvidia/current/nvidia-modprobe.conf /etc/modprobe.d/nvidia-modprobe.conf
	fi
	if [ ! -e /etc/modprobe.d/nvidia-options.conf ]; then
		ln -s /etc/nvidia/current/nvidia-options.conf /etc/modprobe.d/nvidia-options.conf
	fi
	if [ ! -e /etc/modules-load.d/nvidia.conf ]; then
		ln -s /etc/nvidia/current/nvidia-load.conf /etc/modules-load.d/nvidia.conf
	fi
    
}

remove_modprobe_symlinks(){
    echo "rm symlinks" | tee -a $LOG
	rm --force /etc/modprobe.d/nvidia-blacklists-nouveau.conf /etc/modprobe.d/nvidia-modprobe.conf /etc/modprobe.d/nvidia-options.conf /etc/modules-load.d/nvidia.conf
}

create_20_nvidiaconf(){
	if $TEST; then
		return
	fi
	echo "20_nvidia.conf" | tee -a $LOG
	
	 echo "Section \"Device\"" >/etc/X11/xorg.conf.d/20-nvidia.conf
     echo "Identifier \"Nvidia Card\"" >>/etc/X11/xorg.conf.d/20-nvidia.conf
     echo "Driver \"nvidia\"" >>/etc/X11/xorg.conf.d/20-nvidia.conf
     echo "VendorName \"NVIDIA Corporation\"" >>/etc/X11/xorg.conf.d/20-nvidia.conf
     echo "EndSection" >>/etc/X11/xorg.conf.d/20-nvidia.conf
     #echo "Option \"RegistryDwords\" \"EnableBrightnessControl=1\"" >>/etc/X11/xorg.conf.d/20-nvidia.conf
}

remove_20_nvidiaconf(){
	if $TEST; then
		return
	fi
    echo "rm 20-nvidia.conf" | tee -a $LOG
	if [ -e /etc/X11/xorg.conf.d/20-nvidia.conf ]; then
		rm --force /etc/X11/xorg.conf.d/20-nvidia.conf
	fi
}

nvidia_driver_override(){
	echo ""
	## Ask to try installing the latest nvidia driver if graphics card is unknown
    echo $(eval_gettext "Try latest nvidia-driver?") | tee -a $LOG
    echo "" | tee -a $LOG
    echo 1: $(eval_gettext "Yes") | tee -a $LOG
    echo 2: $(eval_gettext "No") | tee -a $LOG
    echo "" | tee -a $LOG
    echo $(eval_gettext "Enter Number of selection") | tee -a $LOG
    read -n 1 -e x

    case $x in
       1) echo "" | tee -a $LOG
          DRIVER="nvidia-driver";;
       2) echo $(eval_gettext "exiting")... | tee -a $LOG && exit 0 ;;
       *) echo $(eval_gettext "invalid option.")  $(eval_gettext "exiting")... | tee -a $LOG && exit 0;;
    esac
    echo ""
}

set_up_pin_file(){
  cp /usr/share/ddm-mx/apt/ddm* /etc/apt/preferences.d
  sed -i "s/VERSION/$1/" /etc/apt/preferences.d/ddm-version-temp
}

choose_version_nvidia(){

declare -a list
#Offer all versions of nvidia-driver available in repository
echo $(eval_gettext "Available Nvidia Developer Repo Versions") | tee -a $LOG
readarray -t list < <(apt-cache madison nvidia-driver |awk '{print $3}' |grep -v deb |grep -v mx)
#Disable the Nvidia repo, menu options
list[${#list[@]}]=$(eval_gettext "Disable Nvidia Developer Repo (default)")
list[${#list[@]}]=$(eval_gettext "quit")

#size of array
#echo "size of array is " "${#list[@]}"

for i in ${!list[@]}; do
  echo "$i - ${list[$i]}" | tee -a $LOG
done

#user enters a number corresponding to the the driver version they want
echo $(eval_gettext "Enter Number of selection") | tee -a $LOG

read -e x

#validate string

case $x in
   #check for not a number, or a null
   #Option chosen is invalid
  *[!0-9]*) echo $(eval_gettext "Invalid option") | tee -a $LOG
  choose_version_nvidia  ;;
esac
  
  if [ -z "$x" ]; then
	disable_nvidia_developer_repo
  fi
  	   
  if [[ $x -gt $((${#list[@]}-1)) ]]; then
		  echo $(eval_gettext "Invalid option")
		  choose_version_nvidia
	      else
		  CANDIDATE=${list[$x]}
		  echo $(eval_gettext "Candidate is: ") $VERSION |tee -a $LOG
  fi

#disable Nvidia Repo is next to last
  
  if [[ $x = $((${#list[@]}-2)) ]]; then
	disable_nvidia_developer_repo
  fi

#quit is always last
if [[ $x = $((${#list[@]}-1)) ]]; then
	clean_up
fi
 
set_up_pin_file $CANDIDATE

unset NVIDIA_VERSION

}

disable_nvidia_developer_repo(){

#action to disable the nvidia developer repository
echo "Disable Nvidia Developer Repo" |tee -a $LOG
echo $(eval_gettext "Ok")...| tee -a $LOG 
           SWITCH=""
           BP=""
           NVIDIA_VERSION=$MAIN_NVIDIA
           apt purge -y cuda-keyring
           apt-get update
           #replace nvidia-detect from main repo
           #only install if nvidia-detect was present already (not present on 32 bit systems)
           if [ "$ARCH" = "amd64" ]; then
           	echo $(eval_gettext "Reset nvidia-detect") | tee -a $LOG
          	apt-get remove nvidia-detect -y && apt-get install nvidia-detect -y
           fi
           install_nvidia
}

update_initramfs()
{
if $TEST ; then
	return
fi
echo "update-initramfs"
update-initramfs -u -k all | tee -a $LOG
}

#add grub config & module config
add_nvidia_module_config()
{
	echo ""
	#set up nvidia kernel modules options and grub boot loader options
	echo $(eval_gettext "adding module options and grub config") |tee -a $LOG
	#display and log
	echo 'GRUB_CMDLINE_LINUX="$GRUB_CMDLINE_LINUX nvidia-drm.modeset=1 nvidia-drm.fbdev=1" > /etc/default/grub.d/nvidia-modeset.cfg' |tee -a $LOG
	echo 'options nvidia NVreg_PreserveVideoMemoryAllocations=1 > /etc/modprobe.d/nvidia-power-management.conf' |tee -a $LOG
	
	echo 'GRUB_CMDLINE_LINUX="$GRUB_CMDLINE_LINUX nvidia-drm.modeset=1 nvidia-drm.fbdev=1"' > /etc/default/grub.d/nvidia-modeset.cfg
	echo 'options nvidia NVreg_PreserveVideoMemoryAllocations=1' > /etc/modprobe.d/nvidia-power-management.conf
	command -v update-grub && update-grub
	
}

#reverse nvidia module changes
remove_nvidia_module_config()
{
    echo ""
    ##remove nvidia kernel modules options and grub boot loader options
	echo $(eval_gettext "removing module options and grub config")
	echo "rm /etc/default/grub.d/nvidia-modeset.cfg" |tee -a $LOG
	echo "rm /etc/modprobe.d/nvidia-power-management.conf" |tee -a $LOG
	rm -f /etc/default/grub.d/nvidia-modeset.cfg
	rm -f /etc/modprobe.d/nvidia-power-management.conf
	command -v update-grub && update-grub
}


main "$@"


