#! /bin/sh
# preinst script for libnvidia-gl-550
#
# see: dh_installdeb(1)
#
# Copyright (C) 2018 Canonical Ltd
# Authors: Alberto Milone

set -e

# summary of how this script can be called:
#        * <new-preinst> `install'
#        * <new-preinst> `install' <old-version>
#        * <new-preinst> `upgrade' <old-version>
#        * <old-preinst> `abort-upgrade' <new-version>
#
# For details see /usr/share/doc/packaging-manual/

library_dir=usr/lib/x86_64-linux-gnu
no_alternatives_version=390.25-0ubuntu1
package_name=libnvidia-gl-550
this_version=`dpkg-query -W -f='${Version}' $package_name | cut -d\: -f2`


_remove_diversions() {
    set -a "libGL.so.1" "libGL.so" "libEGL.so.1" "libEGL.so"
    while [ $# -ge 1 ]; do
        libname=$1
        if dpkg-divert --list | grep -F "/$library_dir/$libname.distrib"
        then
            dpkg-divert --remove --rename /$library_dir/$libname
        fi
        shift
    done
}


_remove_alternative () {
    NAME=$1
    if [ -n "`update-alternatives --list $NAME 2>/dev/null`" ]; then
        set -a `update-alternatives --list $NAME 2>/dev/null`
        while [ $# -ge 1 ] && [ "$#" != "configure" ]; do
            ALTERNATIVE=${1}
            update-alternatives --remove $NAME $ALTERNATIVE
            shift
        done
    fi
}


_remove_alternatives () {
    # Clean up any previous non-multi-arch alternatives
    _remove_alternative gl_conf

    # Clean up the most recent alternatives
    _remove_alternative x86_64-linux-gnu_gl_conf
    _remove_alternative x86_64-linux-gnu_egl_conf

    # Clean up the compatibility alternatives
    if [ "`dpkg --print-architecture`" = "amd64" ]; then
        _remove_alternative i386-linux-gnu_gl_conf
        _remove_alternative i386-linux-gnu_egl_conf
    fi

    # Remove the alternative for glamor-egl
    _remove_alternative glamor_conf

    # explicit ldconfig due to alternatives
    ldconfig
}


_clean_up () {
    # Make sure that no diversion is still there
    _remove_diversions

    # Remove any nvidia related alternatives
    _remove_alternatives
}


case "$1" in
    install|upgrade)
        old_version="$2"
        if dpkg --compare-versions "$old_version" lt "$no_alternatives_version"; then
            # Clean up debris from previous nvidia packages
            _clean_up
        fi
    ;;

    abort-upgrade)
    ;;

    *)
        echo "preinst called with unknown argument \`$1'" >&2
        exit 0
    ;;
esac


# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.



exit 0
