#!/bin/bash
#
# pkgfoster 2005-11-27
# Jukka Heino <jukka@karsikkopuu.net>
#
# pkgfoster is a simple script you can use to clean up orphaned packages (i.e. 
# packages which do not appear in the "Depends on: " line of any other installed
# package). It uses prt-cache by default, so remember to build the cache with
# "prt-get cache". You can also use normal prt-get by modifying the PRT_GET
# variable. The file ~/.config/pkgfoster.keep contains a list of all packages
# you've decided to keep. Packages from core are never considered for deletion.
#

PRT_GET=prt-cache
RECHECK=1

if [ $UID = 0 ]; then
	PKGRM=pkgrm
else
	if command -v doas; then
		PKGRM="doas pkgrm"
	elif command -v sudo; then
		PKGRM="sudo pkgrm"
	else
		PKGRM="su -c pkgrm"
	fi
fi

BASE=$(awk '/^[[:space:]]*prtdir.*\/core/ {print $2}' /etc/prt-get.conf)
CONF="${XDG_CONFIG_HOME:="$HOME/.config"}/pkgfoster.keep"
if [ ! -f "$CONF" ]; then
	mkdir -p "${XDG_CONFIG_HOME}"
	touch "$CONF"
fi

while [ $RECHECK = 1 ] ; do
	echo
	echo "(Re-)checking packages for orphans..."
	RECHECK=0

	mapfile -t orphans < <(comm -23 <($PRT_GET listorphans | sort) \
		<(cat <(find "$BASE" -maxdepth 1 -type d -printf "%f\n") "$CONF" \
		| sort -u) )

	for PACKAGE in ${orphans[@]}; do
		echo
		$PRT_GET info "$PACKAGE"
		echo

		echo -n "Uninstall $PACKAGE? (y/N) "
		read -r ANSWER

		if [ "$ANSWER" = "y" ] ; then
			$PKGRM "$PACKAGE"
			RECHECK=1
		else
			echo "$PACKAGE" >> "$CONF"
		fi
	done

done
