#!/usr/bin/bash
set -e

source /etc/os-release
UPGRADE_FROM="$1"
if [ -z "$UPGRADE_FROM" ]; then
        UPGRADE_FROM=$(("$VERSION_ID"-1))
fi
UPGRADE_TO="$VERSION_ID"
echo "Looking for retired packages betweeen Fedora $UPGRADE_FROM and Fedora $UPGRADE_TO"
echo "Retired packages are no longer maintained. Answer N to the following questions to keep them,"
echo "but these packages will not get any updates. Not even security updates."

TO_REMOVE=$(mktemp --tmpdir retired-packages.XXXXXXXXX)
OLD_LIST=$(mktemp --tmpdir retired-packages.XXXXXXXXX)
NEW_LIST=$(mktemp --tmpdir retired-packages.XXXXXXXXX)




#--repo={fedora,fedora-modular,updates,updates-modular}-source


echo "Gathering package list for Fedora $UPGRADE_FROM"
# in case the metadata are signed and GPG key is not yet imported
dnf repoquery -q --releasever "$UPGRADE_FROM" --disableplugin=local XXXXXXXXXXXX
dnf repoquery -q --releasever "$UPGRADE_FROM" --disableplugin=local --qf="%{name}" | sort > "$OLD_LIST"
#repoquery --releasever "$UPGRADE_FROM" --arch src -a | pkgname | sort | uniq > "$OLD_LIST"
echo "Gathering package list for Fedora $UPGRADE_TO"
# in case the metadata are signed and GPG key is not yet imported
dnf repoquery -q --releasever "$UPGRADE_TO" --disableplugin=local XXXXXXXXXXXX
dnf repoquery -q --releasever "$UPGRADE_TO" --disableplugin=local --qf="%{name}" | sort > "$NEW_LIST"
comm -23 "$OLD_LIST" "$NEW_LIST" > "$TO_REMOVE"

echo "Asking for super user access:"
sudo true

echo "These packages have been retired:"
for PACKAGE in $( cat "$TO_REMOVE"); do
        #skip if this package is not installed
        rpm -q "$PACKAGE" 2>/dev/null >&2 || continue

        SUMMARY=$(rpm -q --qf "%{summary}" "$PACKAGE" | head -n1 )
        echo "$PACKAGE: $SUMMARY"
done

for PACKAGE in $( cat "$TO_REMOVE"); do
        #skip if this package is not installed
        rpm -q "$PACKAGE" 2>/dev/null >&2 || continue

        SUMMARY=$(rpm -q --qf "%{summary}" "$PACKAGE" | head -n1 )
        echo "Removing $PACKAGE: $SUMMARY"
        sudo dnf remove "$PACKAGE"
done

# cleanup
rm -f "$TO_REMOVE" "$OLD_LIST" "$NEW_LIST"
