#!/bin/bash
#
CMD=$(basename "$0")

set -e -u

cleanup()
{
	rm -f $inst_mod $inst_rel
}


# (MAIN)

for input in $1 suggested-removed/$1
do
	[ -f $input ] && break
done

inst_mod=$CMD-mod.tmp
inst_rel=$CMD-rel.tmp
fmt="%-24s # %s\n"

trap "cleanup" EXIT

cleanup

cat $input | while read line 
do
	case $line in
	  "")		echo "$line"; continue ;;	# copy: empty lines
	  \#\#*)	continue ;;			# skip: automated comment lines
	  \#*)		echo "$line"; continue ;;	# copy: comments
	esac

	pkg=$(echo "$line" | sed -e 's/\s.*//')

	found=$(grep " install .* $pkg$" /etc/kusa/installhistory || :)
	[ "X$found" = "X" ] && {
		if dpkg -l $pkg 2>/dev/null | grep -q "^ii"
		then
			echo "$pkg" >>$inst_rel
		else
			echo "$pkg"
		fi
		continue
	}
	mod=$(echo "$found" | tail -1 | cut -d' ' -f3)
	printf "$fmt" "$pkg" "$mod" >>$inst_mod
done

echo  "
## INSTALLED BY MODULES
##"
cat $inst_mod

echo "
## INSTALLED (RELATED)
##"
cat $inst_rel

exit 0
