#!/bin/bash
#
# __copy1__
# __copy2__
#
CMD=`basename $0`
_rot=

export BACKUPDIR=/etc/backup
export MODNAME=
export TOOLKIT=${TOOLKIT:-"kusa"}
export CONFDIR=${CONFDIR:-"/etc/$TOOLKIT"}
export INSTALLHISTORY="$CONFDIR/installhistory"
export F_DEBUG=false

. $TOOLKIT-functions.sh || exit 1

rot()
{
	case $_rot in
	 '|') _rot='/' ;;
	 '/') _rot='-' ;;
	 '-') _rot='\\' ;;
	 *)   _rot='|' ;;
	esac
	echo -en "${_rot}[D" >&2
}

usage()
{
	echo -e "\nusage: $CMD [-n] [-D] module(s) ...\n" >&2
	exit 1
}

# (MAIN)

f_allmodules=false
f_exec=true
command="apt-get --yes autoremove"
xargs_flags="-t"
reqmodules=

[ x"$1" = "x-n" ] && {
	f_exec=false
	command="echo"
	xargs_flags=""
	shift
}
[ x"$1" = "x-D" ] && {
	F_DEBUG=true
	shift
}

case "$1" in
  -a)		f_allmodules=true ;;
  -*|"")	usage ;;
esac

match=
$f_allmodules || {
	match="${match}($1"
	reqmodules="$1"
	shift
	for module in $*
	do
		match="$match|$module"
		reqmodules="$reqmodules $module"
	done
	match="${match}) "
}

# remove packages of requested modules
#
echo -en " checking pkgs " >&2

egrep " install $match" $INSTALLHISTORY | while read date ii module pkg
do
	rot
	is_installed $pkg || continue
	echo $pkg
	echo -n . >&2
	echo "`date '+%y%m%d%M%S'` remove $module $pkg" >>$INSTALLHISTORY
done | xargs --no-run-if-empty $xargs_flags $command
echo


# purge them, too
#
echo -en " purging pkgs " >&2

egrep " install $match" $INSTALLHISTORY | while read date ii module pkg
do
	rot
	is_installed $pkg || continue
	echo $pkg
	echo -n . >&2
done | xargs --no-run-if-empty $xargs_flags dpkg --purge 2>/dev/null >/dev/null
echo


echo -e " cleaning files ..." >&2

egrep " in_file $match" $INSTALLHISTORY | while read date ii MODNAME file
do
	uninstallfiles "$file"
done
echo


# final cleanups
#
$f_exec && {
	$command
	if $f_allmodules
	then
		rm -f $CONFDIR/done/*
	else
		for module in $reqmodules
		do
			rm -f "$CONFDIR/done/$module.done"
		done
	fi
}

exit 0
