#!/bin/bash

# AstraLinux SE 1.6, AstraLinux CE 2.12, Ubuntu 18.04, nvidia/nouveau driver uninstaller
# ======================================================================================
# Recommended before binary(closed,proprietary) nvidia driver install
# Author: Alexey Kovin <4l3xk3@gmail.com>
# All rights reserved
# Russia, Electrostal, 2018
set -ue
. gettext.sh
export TEXTDOMAINDIR=/usr/share/locale
export TEXTDOMAIN="astra-nvidia-uninstall"

# Check EUID
# ----------
echo "EUID=$EUID"
if [ x"$EUID" != "x0" ]; then
    gettext "Launch program as administrator (sudo) (root) .."; echo
    exit 1
fi

# Xorg config
# -----------
gettext "Removing xorg.conf .."; echo
if [ -f /etc/X11/xorg.conf ]; then
    mv -f /etc/X11/xorg.conf /etc/X11/backup-$$-xorg.conf-backup
    eval_gettext '/etc/X11/xorg.conf removed, backup version: /etc/X11/backup-$$-xorg.conf-backup'; echo
fi
dpkg-reconfigure xserver-xorg


# Uninstall deb packets
# ---------------------
gettext "Find and uninstall nvidia packets .."; echo
apt remove --purge --yes --force-yes nvidia*
apt remove --purge --yes --force-yes libnvidia*
apt remove --purge --yes --force-yes xserver-xorg-video-n*
for nvdeb in `dpkg -l | grep nvidia`; do
    gettext "Removing packet $nvdeb .."; echo
    apt remove --purge --yes --force-yes $nvdeb
done

# Restore original mesa libs and sysmlinks
# ----------------------------------------
gettext "Restore original mesa GL libs and symlinks"; echo
sudo apt install --reinstall --yes --force-yes xserver-xorg-core libgl1 libgl1-mesa-dri libgl1-mesa-glx libglapi-mesa libgles2 libgles2-mesa libglew2.0 libglewmx1.13 libglu1-mesa libglvnd0 libglx-mesa0 libglx0


# Kernel modules
# --------------
gettext "Find and uninstall nvidia drivers .."; echo
for nvdriver in `find /lib/modules -type f -name "nvidia*"`; do
    echo "$nvdriver"
    mv -f $nvdriver ${nvdriver}-$$-backup
done

depmod -a
sed -i -e "/[[:space:]]*blacklist[[:space:]]\+nouveau/d" /etc/modprobe.d/blacklist.conf
sed -i -e "/[[:space:]]*options[[:space:]]\+nouveau[[:space:]]\+modeset[[:space:]]*=[[:space:]]*0/d" /etc/modprobe.d/blacklist.conf
sed -i -e "s/^#[[:space:]]*nouveau[[:space:]]\+modeset[[:space:]]*=[[:space:]]*1/nouveau modeset=1/" /etc/initramfs-tools/modules

update-initramfs -u -k all

gettext "Reboot computer to apply changes"; echo
