#!/bin/bash

set -e

# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package
#

# Function to remove diversions for a given package
remove_divert() {
    local PKG="$1"
    if [ -z "$PKG" ]; then
        echo "Usage: remove_divert <package-name>" >&2
        return 1
    fi

    # Get all diversions for the package
    local DIVERSIONS
    DIVERSIONS=$(LANG=C /usr/bin/dpkg-divert --list "$PKG" | awk '{print $3, $5}')

    if [ -z "$DIVERSIONS" ]; then
        return 0
    fi

    while read -r ORIGINAL DIVERTED; do
        # Remove the diversion (explicitly use --no-rename for future dpkg versions)
        /usr/bin/dpkg-divert --remove --package "$PKG" --no-rename "$ORIGINAL" || true

        # If the original file doesn't exist, restore from the diverted file
        if [ ! -e "$ORIGINAL" ] && [ -e "$DIVERTED" ]; then
            /bin/cp -a "$DIVERTED" "$ORIGINAL" || true
        fi

        # Remove the diverted file if it exists
        if [ -e "$DIVERTED" ]; then
            /bin/rm -f "$DIVERTED" || true
        fi
    done <<< "$DIVERSIONS"
}

case "$1" in
    remove|purge)
    # Remove diversions
    remove_divert 'chromium-solydxk-adjustments'
    ;;
    *)
    ;;
esac

#DEBHELPER#

exit 0
