#!/bin/sh
# This script is called from the postinst of all libgl1-nvidia{,-legacy-*}-glx{,-ia32} 
# and xserver-xorg-video-nvidia* packages.
set -e

. /usr/share/debconf/confmodule

package="nvidia-installer-cleanup"
templates="$(dpkg-query --control-path "$package" templates)"
if [ -n "$templates" ]; then
	db_x_loadtemplatefile "$templates" "$package"
fi


# dpkg-reconfigure does not set DPKG_MAINTSCRIPT_PACKAGE (#565317)
if [ -z "$DPKG_MAINTSCRIPT_PACKAGE" ]
then
	echo "ERROR: DPKG_MAINTSCRIPT_PACKAGE is not set, usually a bug in dpkg-reconfigure"
	exit 1
fi

case "$DPKG_MAINTSCRIPT_PACKAGE" in
	xserver-xorg-video*)
		libdir="/usr/lib/xorg/modules/extensions"
		pattern="libglx.so.*"
		;;
	*-ia32*)
		libdir="/usr/lib32"
		pattern="libGL.so.*.*"
		;;
	*)
		libdir="/usr/lib"
		pattern="libGL.so.*.*"
		;;
esac

CONFLICT_LIBS=""
for f in "$libdir"/$pattern "$libdir"/i386-linux-gnu/$pattern "$libdir"/x86_64-linux-gnu/$pattern "$libdir"/arm-linux-gnueabihf/$pattern /usr/lib32/libGL.so*
do
	if [ -e "$f" ] || [ -L "$f" ]
	then
		if dpkg-query -S "$f" >/dev/null 2>&1
		then
			echo "ERROR: The conflicting library '$f' is known to dpkg." >&2
			dpkg-query -S "$f" >&2
			exit 1
		fi
		CONFLICT_LIBS="$CONFLICT_LIBS $f"
	fi
done
CONFLICT_LIBS="${CONFLICT_LIBS#[ ]}"

if [ -n "$CONFLICT_LIBS" ]; then
	db_subst nvidia-installer-cleanup/remove-conflicting-libraries conflict-libs "$CONFLICT_LIBS"
	db_fset nvidia-installer-cleanup/remove-conflicting-libraries seen false
	# The following command intentionally fails in DEBIAN_FRONTEND=noninteractive mode.
	db_input high nvidia-installer-cleanup/remove-conflicting-libraries
	db_go
	db_get nvidia-installer-cleanup/remove-conflicting-libraries
	if [ "$RET" = "true" ]; then
		backupdir=$(mktemp -d /var/tmp/nvidia-backup.XXXXXX)
		mv $CONFLICT_LIBS "$backupdir"
		echo "Moved the conflicting libraries '$CONFLICT_LIBS' to '$backupdir'."
		unset backupdir
		# fix possibly broken link
		dpkg-trigger /usr/libGL.so.1
		dpkg-trigger register-alternative-glx-nvidia
	else
		echo "ERROR: The conflicting libraries '$CONFLICT_LIBS' still exist." >&2
		exit 1
	fi
fi


exit 0