#!/bin/bash

#  Name:    rmvpkg
#  Author:  Terry Neve
#  Created: Jan 2017
#
#  Program to remove developement packages installed during package build
#  process.  It takes the *.remove file created by br-install (or an older
#  apt-get log created by addpkg) and removes the listed packages that are
#  still installed in a single "dnf5 remove".
#  It is designed to be called via Right-Click service menu in pkgutils.
#
#  Revisions:
#       2017012.01  Initial working version
#       20260531.01 Switch from APT to DNF
#       20260919.01 Remove by package name instead of undoing transactions
#       20260919.02 Accept older apt-get style .remove files

REMOVE_FILE=$1
HEADER="# pkgutils-remove v1"

if [ ! -f "$REMOVE_FILE" ]; then
    echo "Usage: $0 <specname.spec.remove>"
    exit 1
fi

# Print the package names listed in the .remove file
list_packages () {
    if [ "$(head -n 1 "$REMOVE_FILE")" = "$HEADER" ]; then
        # br-install format: skip comments and blank lines
        grep -v -e '^#' -e '^[[:space:]]*$' "$REMOVE_FILE"
    else
        # addpkg format: apt-get output, names are in the indented lines
        # after "The following NEW packages will be installed:"
        awk '/^The following NEW packages will be installed:/ { n = 1; next }
             n && /^[[:space:]]/ {
                 for (i = 1; i <= NF; i++)
                     if ($i !~ /^\(/ && $i !~ /\)$/) print $i
                 next
             }
             { n = 0 }' "$REMOVE_FILE"
    fi
}

NAMES=$(list_packages | sort -u)
if [ -z "$NAMES" ]; then
    echo "Error: no packages found in $REMOVE_FILE (unsupported format?)"
    exit 1
fi

echo "Cleaning up build dependencies from $REMOVE_FILE..."

PKGS=()
while read -r name; do
    if rpm -q --quiet "$name"; then
        PKGS+=("$name")
    else
        echo "Already removed: $name"
    fi
done <<< "$NAMES"

if [ ${#PKGS[@]} -eq 0 ]; then
    echo "Nothing to remove."
    exit 0
fi

# One transaction; dnf5 lists everything affected and asks for confirmation
if ! su -c "dnf5 remove $(printf '%q ' "${PKGS[@]}")"; then
    echo "Error: dnf5 remove failed or was cancelled."
    exit 1
fi

echo "Cleanup complete."
