#!/bin/sh

set -e

remove_corrupt_alternative()
{
	local alt=$1

	if [ -f /var/lib/dpkg/alternatives/$alt ] && \
		! update-alternatives --query $alt >/dev/null 2>&1
	then
		# file exists, but query failed? likely corrupt!
		echo "Removing corrupt alternative(s) '$alt'"
		update-alternatives --remove-all $alt >/dev/null 2>&1 || \
			rm -fv /var/lib/dpkg/alternatives/$alt
	fi
}

remove_obsolete_alternative()
{
	local alt=$1

	remove_corrupt_alternative $alt

	if update-alternatives --query $alt >/dev/null 2>&1
	then
		echo "Removing obsolete alternative(s) '$alt'"
		update-alternatives --remove-all $alt
	fi
}

if [ "$1" = "install" ] || [ "$1" = "upgrade" ]; then

	if dpkg --compare-versions "$2" lt "3.1.3-10~" ; then

		# Recover from historically grown corruption (#912437)
		remove_corrupt_alternative mpi
		remove_corrupt_alternative mpi-@TRIPLET@

		# mpicc seemed to be used as a master alternative by some MPI package. But
		# currently, all MPI packages have the mpicc alternative installed as a slave
		# link. We remove the link here in order to resolve bugs #531184 and #532910.
		remove_obsolete_alternative mpicc

		# Similarly, see #886644
		remove_obsolete_alternative mpiCC

		# Splitting mpi and mpi-$MULTIARCH requires this
		if update-alternatives --query mpi 2>/dev/null | grep -q mpi-fort.pc ; then
			echo "Removing pre-multiarch 'mpi' alternative(s)"
			update-alternatives --remove-all mpi
			update-alternatives --remove-all mpi-@TRIPLET@ 2>/dev/null || true
		fi

		# This may be left hanging on the upgrade to multi-arch.
		rm -fv /usr/lib/libpmix.so

	fi

fi

#DEBHELPER#
