#!/bin/bash

set -e

# 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 'solydxk-system'
        
        # Remove any symlings to the SolydXK logos
        find /usr/share/icons -type l -iname "*solyd*" ! -path "*evolvere-additional*" -delete
        
        # Remove gnupg configuration from skel
        GNUPG='/etc/skel/.gnupg'
        if [ -d "$GNUPG" ]; then
            rm -rf "$GNUPG"
        fi

    ;;
    upgrade|failed-upgrade|abort-install|abort-upgrade|disappear)
    ;;
    *)
        echo "postrm called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

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

#DEBHELPER#

exit 0

