#!/bin/sh

readonly XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}"
readonly EXCLUDE_CONF="$XDG_CONFIG_HOME/${0##*/}"
readonly DIALOG=bsddialog
readonly LINES=$(($(stty size | cut -d" " -f1)-5))

exclude_opt=0	# exclude packages list generation mode
new_leafs_yes=0	# automatically seek new leafs after pkg removal
rm_count=0	# removed packages counter
sel_status="off" # default packages selection state (on|off)
tmpdir="" # directory for temporary files

display_usage() {
	<< EOF >&2 cat
Usage: ${0##*/} -h
       ${0##*/} [-oy]
       ${0##*/} -x

    -h - show this help
    -o - set selection to on by default
    -x - update exclude list
    -y - assume yes when there are new leaf packages

EOF
	exit 1
}

get_leafs_data() {
	pkg-static query -e '%#r = 0 && %n !~ FreeBSD-*' '%n-%v@%sb@%c | Installed: %t' | \
		awk '
			{
				"date -r "$NF | getline date;
				close("date -r "$NF);
				gsub($NF, date);
				gsub(" ", "%SPC%");
				print;
			}' > "$tmpdir/data"
}

item_prepare() {
	local pkg=${1%%@*}
	local bytes=$(echo $1 | awk -F@ '{ print $2 }')
	local desc=$(echo $1 | awk -F@ '{ gsub("%SPC%", " "); print $3 }')
	local size=$(printf '%8s' "$(number_humanize $bytes)")

	echo "$pkg \"$size\" \"$2\" \"$desc\"" >> "$tmpdir/items"
}

mktmp() {
	local tmp=$(mktemp -dt "${0##*/}")

	if [ ! "$tmp" ]; then
		echo "===> Failed to create temporary directory" >&2
		exit 1
	fi
	echo "$tmp"
}

number_humanize() {
	echo "$1" | awk '{
		bytes = $0;
		gb=2^30; mb=2^20; kb=2^10;

		if (bytes > gb) {
			size = bytes/gb;
			unit = "GB";
		} else if (bytes > mb) {
			size = bytes/mb;
			unit = "MB";
		} else if (bytes > kb) {
			size = bytes/kb;
			unit = "kB";
		} else {
			size = bytes;
			unit = "B ";
		}
		if (unit == "GB" || unit == "MB")
			printf "%.1f %s", size, unit;
		else
			printf "%.0f %s", size, unit;
	}'
}

update_exclude_list() {
	local count=0 line status

	get_leafs_data

	for line in $(cat "$tmpdir/data"); do
		status="off"
		case $pkg_exclude in *${line%@*}*) status="on" ;; esac
		item_prepare $line $status
		count=$((count+1))
	done

	xargs -o $DIALOG \
		--item-bottom-desc \
		--separate-output \
		--title "pkg-deleaf" \
		--clear-screen \
		--checklist "Select packages to exclude ($count items):" $LINES 0 $LINES \
		< "$tmpdir/items" 2> "$tmpdir/selected"

	if [ -s "$tmpdir/selected" ]; then
		[ -d "$XDG_CONFIG_HOME" ] || mkdir "$XDG_CONFIG_HOME"
		mv "$tmpdir/selected" "$EXCLUDE_CONF"
	fi

	rm -r "$tmpdir"
	exit 0
}

while getopts "hoxy" option; do
	case $option in
	o)
		[ $exclude_opt -eq 1 ] && display_usage
		sel_status="on" ;;
	x)
		[ "$sel_status" = "on" -o $new_leafs_yes -eq 1 ] && display_usage
		exclude_opt=1 ;;
	y)
		new_leafs_yes=1 ;;
	*)
		display_usage
	esac
done

if [ $(id -u) -ne 0 ]; then
	if ! which -s sudo; then
		echo "===> sudo not found" >&2
		echo "===> This script requires root privileges or properly configured sudo." >&2
		exit 1
	fi
	SUDO="sudo"
fi

if ! which -s $DIALOG; then
	echo "===> Required $DIALOG not found." >&2
	exit 1
fi

tmpdir=$(mktmp)

[ -f "$EXCLUDE_CONF" ] && pkg_exclude=$(grep -v '^#' "$EXCLUDE_CONF")
[ $exclude_opt -eq 1 ] && update_exclude_list

$DIALOG --title "pkg-deleaf" --infobox "Checking for leaf packages..." 3 34

while true; do
	count=0

	cat /dev/null > "$tmpdir/items"
	get_leafs_data

	for line in $(cat "$tmpdir/data"); do
		pkg=${line%%@*}

		case $pkg_seen in *$pkg*) continue;; esac
		pkg_seen="$pkg_seen $pkg"

		case $pkg_exclude in *${pkg%-*}*) continue;; esac
		[ ${pkg%-*} != "pkg" ] || continue

		item_prepare $line $sel_status
		count=$((count+1))
	done
	[ -s "$tmpdir/items" ] || break

	if [ $rm_count -gt 0 -a $new_leafs_yes -eq 0 ]; then
			$DIALOG --yesno "There are new leaf packages. Continue?" 5 43
			[ $? -eq 0 ] || break
	fi

	xargs -o $DIALOG \
		--item-bottom-desc \
		--separate-output \
		--title "pkg-deleaf" \
		--clear-screen \
		--checklist "Select packages to remove ($count items):" $LINES 0 $LINES \
		< "$tmpdir/items" 2> "$tmpdir/selected"

	ret=$(cat "$tmpdir/selected")
	[ -n "$ret" ] || break

	list=$(pkg-static query '%sb' $ret)
	$SUDO pkg-static delete -y $ret || break

	for bytes in $list; do
		rm_freed=$((rm_freed+bytes));
		rm_count=$((rm_count+1));
	done
done

rm -r "$tmpdir"

[ "$pkg_seen" ] || echo "===> No leaf packages to remove"

[ "$rm_count" -gt 0 ] &&
	echo "===> Packages removed: $rm_count  Disk space freed: $(number_humanize $rm_freed)"
