#!/bin/sh
#
# Copyright (c) 2026 Alexander Wittig <alexander@wittig.name>
# Copyright (c) 2005 Timothy Redaelli <drizzt@freesbie.org>
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.

# Interactive script for deinstalling "leaf" packages
#
# Syntax: pkg_rmleaves [-l]
# Options:
#	-l: List leaf packages only, don't ask if they should be deinstalled

TMPDIR=`mktemp -dt pkg_rmleaves`	# Directory for temporary files
TMPFILE="$TMPDIR/tmp"				# Generic use temporary file
DLGFILE="$TMPDIR/dlg"				# Filtered Dialog arguments
PKGFILE="$TMPDIR/pkgs"				# Unfiltered package file
PREV="$TMPDIR/prev"					# Previous unfiltered leaves file

PKGDIR="/var/db/pkg"                # Where legacy pkg_* stores its database

# print a message into stderr, delete TMPDIR and exit
esci() {
	echo "$1" >&2
	rm -r "$TMPDIR"
	exit $2
}

# update leaf files
checkLeafs() {
	pkg query -e '%#r = 0' '#&quot;#%n-%v#&quot;# #&quot;#%sh#&quot;# #&quot;#off#&quot;# #&quot;#%c#&quot;#' \
	| sort | sed -e "y/\"/'/" -e 's/#&quot;#/"/g' > "$PKGFILE"

	if [ -f "$PREV" ]; then
		comm -1 -3 "$PREV" "$PKGFILE" > "$TMPFILE"
	else
		cp "$PKGFILE" "$TMPFILE"
	fi
	mv "$PKGFILE" "$PREV"
}

# display the list of leaves
showList() {
	cp "$TMPFILE" "$DLGFILE"
	if [ `wc -l <"$DLGFILE"` -le "$MAXPKGS" ]; then
		MSG="These are all leaf packages installed on your system.\nChoose the packages to deinstall:"
	else
		MSG="These are some leaf packages installed on your system. The full list may span multiple dialogs.\nChoose the packages to deinstall:"
	fi
	# Only FBSD 15+
	# xargs -o -L "$MAXPKGS" "$DIALOG" \
	# 	--item-bottom-desc --separate-output --clear-screen --cr-wrap --title "Welcome to pkg_rmleaves" \
	# 	--cancel-exit-code 255 --esc-exit-code 255 \
	# 	--checklist "$MSG" \
	# 	"$MAX" "$MAX" "$LINES" \
	# < "$DLGFILE" 2> "$TMPFILE"
	# For FBSD 14 use ugly shell workaround to change all non-zero exit codes to 255
	xargs -o -L "$MAXPKGS" sh -c "\"$DIALOG\" \
		--item-bottom-desc --separate-output --clear-screen --cr-wrap --title \"Welcome to pkg_rmleaves\" \
		--checklist \"$MSG\" \
		\"$MAX\" \"$MAX\" \"$LINES\" \"\$@\" || exit 255" dummy \
	< "$DLGFILE" 2> "$TMPFILE"

	[ $? -ne 0 ] && esci "Program aborted, no packages deinstalled." 1

	if [ -s "$TMPFILE" ]; then
		pkgs=$(cat "$TMPFILE")
		set -- $pkgs
		i=0
		for p; do
			i=$(($i+1))
			percent=$((100*$i/$#))
			echo "XXX"
			echo "$percent"
			echo "Deinstalling $p"
			echo "XXX"
			eval $PKGDELETE "$p" > /dev/null
                        if [ $i -eq $# ]; then
                                echo EOF
                        fi
		done | "$DIALOG" --clear-screen --gauge "Starting to remove packages" 10 65 0
	fi
}


# Call the functions

# Trap ctrl+c and delete TMPDIR
trap 'esci "Ctrl+C pressed, program aborted!" 1' INT

# Set default values and prepare environment
DIALOG=bsddialog
MAX=0
LINES=13
MAXPKGS=250
PKGDELETE="pkg delete -y -q"

# Dry-run without removing anything (for testing)
#PKGDELETE="sleep 1; echo "

# Handle command line arguments
for i in $(getopt l $*); do
	case "$i" in
		-l)
			checkLeafs
			cat "$TMPFILE"
			esci "Program terminated successfully." 0
			break;;
	esac
done

if ! which -s "$DIALOG"; then
	esci "$DIALOG not found." 1
fi

# The main loop
checkLeafs
[ ! -s "$TMPFILE" ] && esci "No leaves found." 0
while true; do
	showList

	checkLeafs
	[ ! -s "$TMPFILE" ] && esci "No more leaves found." 0

	"$DIALOG" --clear-screen --yesno "Do you want to process the new leaf packages?" $MAX $MAX
	[ $? -ne 0 ] && esci "Program terminated successfully." 0
done
