#!/usr/bin/bash
set -e

source /etc/os-release
if [[ ! "$1" =~ ^[0-9]*$ ]]
then
    echo "usage: $(basename "$0") [fedora linux version number as digits]."
    exit 1
fi
UPGRADE_FROM="$1"
if [ -z "$UPGRADE_FROM" ]; then
        UPGRADE_FROM=$(("$VERSION_ID"-1))
fi
UPGRADE_TO="$VERSION_ID"
echo "Looking for retired packages between Fedora Linux $UPGRADE_FROM and Fedora Linux $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)

function pause() {
   # clear the stdin buffer and pause with question
   read -t 1 -n 10000 discard || [ $? -gt 128 ]
   read -p "Hit Enter to continue with other package or Ctrl + C to interrupt."
}


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


echo "Gathering package list for Fedora Linux $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 Linux $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 Executed from remove-retired-packages

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"
        SRPMFILENAME=$(rpm -q --qf "%{sourcerpm}" "$PACKAGE")
        SRPM=$(rpm-print-name-from-filename "$SRPMFILENAME")
        REASON=$(curl --fail https://src.fedoraproject.org/rpms/$SRPM/raw/rawhide/f/dead.package 2>/dev/null || echo "unknow reason")
        echo "Reason of retirement: $REASON"
        sudo dnf remove "$PACKAGE" || pause
done

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