#!/bin/bash
#
#removedb: version 1.0
#
#a script to remove a tgz dependency tree.
#
#--------------------------------------------------------------


#--------------------------------------------------------------
#aux. functions - useful stuff for the tracing of dependencies

. $INSTDIR/removecore
#--------------------------------------------------------------


#--------------------------------------------------------------
#main body

##retrive the list of all dependency files:
#this is the list of all non read files into the database
DEPFILELIST=(`find $LOGDIR -type f`)

[ ${#DEPFILELIST[@]} -eq 0 ] && {
	echo "no dependency list found in $LOGDIR"
	exit 1
}

USINGLIST=""

YES_NO=""	#just an aux. value for user prompt: it is modified by the function ask_yesno & ask_yesnoall

FILENAMES=`normalizeName $@`

for FILE in $FILENAMES; do
	#retrive file name into packages database
	checkName $FILE
	RET=$?
	if [ $RET -eq 2 ]; then
	#if the file is 'noarch'
		echo -e "PACKAGE NAME:\n$FILE\n"
		[ $AUTO -eq 0 ] && {
			ask_yesno "would you like to remove it [yes/no]? "
		} || {
			YES_NO="yes"
		}

		[ "$YES_NO" = "yes" ] && removepkg $FILE

	elif [ $RET -eq 0 ]; then
		#search for tgz dependant on $FILE
		PKGUSEDBY=(`checkList $FILE`)
		USING=${#PKGUSEDBY[@]}
		#if some file uses the given package we prompt this!
		[ ! $USING -eq 0 ] && hilightDependant $FILE ${PKGUSEDBY[@]}

		#start the remotion core routine
		removecore $FILE ${DEPFILELIST[@]}
		#if we have removed the given tgz
		#we store tgz's dependant on the given tgz (if they exist)
		[ ! $? -eq 1 ] && [ ! $USING -eq 0 ] && USINGLIST=(${USINGLIST[@]} ${PKGUSEDBY[@]})

		#refresh cache
		DEPFILELIST=(`find $LOGDIR -type f`)
	fi
done

#update data for packages still installed but dependant on tgz's we have removed
if [ ! "${USINGLIST[0]}" = "" ]; then {
	echo -e "\nupdating data"
	USINGLIST=(`echo ${USINGLIST[@]} | sed -e 's| |\n|g' | sort | uniq`)	
	rebuildData ${USINGLIST[@]}
}
fi
#rm $DEPFILELIST
echo "...done"
#--------------------------------------------------------------

#EOF
