#! /bin/sh
#
#resync. rssyncronize your dependency database after external install/upgrade/remove operations.
#external = performed via other tools than tracepkg (basic pkgtools, slap-get, swaret and so on...)
#
#the idea for the following script comes from Andrew J. Kroll

#--------------------------------------------------------------
#aux. functions

. $INSTDIR/core-functions

#--------------------------------------------------------------

function resync () {

TRACED="$(ls $LOGDIR)"	#already traced pkgs

TOTRACE=""  #newly installed/upgraded pkgs
TOPURGE=""  #removed pkgs
CHECKED=""	#list of already checked packages

echo "check for removed/updated files..."

#grab any unchanged/removed/updated package
for FILE_ in $TRACED; do

echo "    checking file $FILE_"

[ -f $PKGDIR/$FILE_ ] &&	{
	CHECKED="$CHECKED $FILE_"
	continue
} || {

echo "        file doesn't exist. append it to purge queue"

	#file not found: we put it in purge
	TOPURGE="$TOPURGE $FILE_"
	#retrive package name
	FILE_NAME=`echo $FILE_ | awk -F - '{for (i=1; i<NF-3; i++) {printf $i"-"}; printf $(NF-3)}'`
	CANDIDATES_=$(ls $PKGDIR | grep $FILE_NAME)

echo "        found the following upgrade candidates: $CANDIDATES_"

	for CFILE in $CANDIDATES_; do
		#grab the exact file! and not other matching strings
		CFILE_NAME=`echo $CFILE | awk -F - '{for (i=1; i<NF-3; i++) {printf $i"-"}; printf $(NF-3)}'`
		[ "$CFILE_NAME" = "$FILE_NAME" ] && {
		#we have found an upgrade!
		TOTRACE="$TOTRACE $CFILE"
		CHECKED="$CHECKED $CFILE"

echo "        append the following guessed upgrade to the trace queue: $CFILE"

		#
		#	we could break now but... it is possible to install more than one version per package.
		#	strange but possible scenario, so we continue looping with our script!
		#
		}
	done
}
done

echo "check for newly installed files..."

#check for any newly installed package
UNTRACED="$(ls $PKGDIR | grep -v noarch)" #actual pkg list, without any noarch tgz

#clean list from already checked packages
for FILE_ in $CHECKED; do
	UNTRACED=$(${UNTRACED/$FILE_} 2>/dev/null)

echo "    skipping checked file: $FILE_"

done

#merge remaining packages into the list of untracked packages
TOTRACE="$TOTRACE $UNTRACED"

echo "purge database from obsolete dependency records..."
for FILE_ in $TOPURGE; do
	echo "    purge obsolete file $FILE_"
	removedep $FILE_
done

echo "update database with new dependency records..."
[ -n "$TOTRACE" ] && buildFile "$TOTRACE"

#retrieve pkgs dependant on removed files
echo "retrieve database records dependant on removed files..."
RETRACEABLE=""
for FILE_ in $TOPURGE; do
	RETRACEABLE="$RETRACEABLE $(checkList $FILE_)"
done

RETRACEABLE="$(echo $RETRACEABLE | sed -e 's| |\n|g' | sort | uniq)"
[ -n "$RETRACEABLE" ] && buildFile $RETRACEABLE

echo "checking database records with missing dependencies against newly installed packages..."
[ -n "$UNTRACED" ] && updateData "$UNTRACED"

echo "...done."
}

resync