#!/bin/sh

# support for i18n and L10n
. gettext.sh
export TEXTDOMAIN=install-software-upgrades

RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color

echo "${RED}"
echo "$(gettext "Don't close this window!")"
echo "$(gettext "Please wait until all upgrades have been installed...")"
echo "${NC}"

auplink_check()
{
	# check if auplink is necessary and possible
	if grep -q "aufs / aufs" /proc/mounts
	then
		if [ ! -e /sbin/auplink ]
		then
			echo "$(gettext "WARNING: /sbin/auplink not found. Can't clean up file system. Please install the package \"aufs-tools\".\nPress ENTER to continue...")"
			read blah
		fi
	fi
}

cleanup_fs_and_cache()
{
	# FIXME:
	# auplink flushing crashes much too often (between 5-10 % of all test runs
	# crashed the kernel).
	# Therefore we leave out the auplink part for the time being...

	## clean up aufs pseudo links
	#if grep -q "aufs / aufs" /proc/mounts
	#then
	#	if [ -e /sbin/auplink ]
	#	then
	#		echo "$(gettext "Cleaning up file system, please wait...")"
	#		/sbin/auplink / flush
	#	fi
	#fi

	# empty the package cache
	apt-get clean
}

# FIXME:
# as stated above, auplink is too crashy, therefore disabled for now...
## cleanup before and after installing upgrades
#auplink_check

echo "${RED}"
cleanup_fs_and_cache
echo "${NC}"

apt upgrade -y

echo "${GREEN}"
cleanup_fs_and_cache
echo "${NC}"

get_nvidia_versions() {
	PACKAGE_PATTERN=$1
	echo "$(dpkg -l "$PACKAGE_PATTERN" | grep ^ii | awk {' print $3 '} | sed "s/\(.*\)-.*/\1/g" | sed "s/\./-/g")"
}

sync_nvidia_flatpak() {
	for NVIDIA_VERSION in $(get_nvidia_versions "nvidia-driver") $(get_nvidia_versions "nvidia-legacy-*xx-driver")
	do
		if ! flatpak list | grep -q org.freedesktop.Platform.GL.nvidia-${NVIDIA_VERSION}
		then
			flatpak install -y org.freedesktop.Platform.GL.nvidia-${NVIDIA_VERSION}
		fi
	done
}

if command -v flatpak > /dev/null
then
	flatpak --noninteractive update
	# For some (so far unknown) reasons the installation of an nvidia flatpak
	# driver sometimes fails at the first attempt but works fine when trying
	# again. Therefore we run sync_nvidia_flatpak twice here.
	sync_nvidia_flatpak
	sync_nvidia_flatpak
fi
