#!/bin/bash
#
#retrivedb: version 1.0
#
#a script containing some useful functions used to trace dependencies of a tgz
#
#usage:
#
#./retrivedb packagename
#
#pkgname is the name of the tgz package inside the slack database
#
#BUG: ??? probably...
#--------------------------------------------------------------


#--------------------------------------------------------------
#aux. functions - useful stuff for the tracing of dependencies
. $INSTDIR/core-functions
#--------------------------------------------------------------


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


echo "gathering information. Please, wait..."

#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
}

#retrive all dependencies (including repeated ones...)
DEPMIX=(`retriveRoutine $1 ${DEPFILELIST[@]}`)

DEPTREE=(`echo ${DEPMIX[@]} | cut -f1 -d %`)
DEPFILELIST=(`echo ${DEPMIX[@]} | cut -f2 -d %`)

if [ ${#DEPTREE[@]} -eq 0 ]; then
	echo -e "\nPACKAGE NAME:\n$1"
	echo "hasn't any dependency list into $LOGDIR"
 	exit 0;
fi

DEPTREE=(`echo ${DEPTREE[@]} | sed -e 's/ /\n/g' | sort | uniq`)

#mark dependencies as shared (with other packages) or unshared
#CWD=`pwd`
#cd /$LOGDIR
unset SHARED
for ((i=0; i<${#DEPTREE[@]}; i++)); do
	echo ${DEPFILELIST[@]} | xargs grep -m1 ${DEPTREE[$i]} > /dev/null
	if [ ! $? -eq 0 ]; then
		#not shared
		SHARED[$i]=0;
	else
		#shared
		SHARED[$i]=1;
	fi
done

#cd $CWD

##if we have shared dependencies, also their dependencies are shared...
loopShared ${DEPTREE[@]}

#print results...
echo -e "\nPACKAGE NAME:\n$1"

echo -e "\nNOT SHARED DEPENDENCIES:"

for ((j=0; j<i; j++)); do
	if [ ${SHARED[$j]} -eq 0 ]; then
		echo ${DEPTREE[$j]}
	fi
done

echo -e "\nSHARED DEPENDENCIES:"

for ((j=0; j<i; j++)); do
	if [ ! ${SHARED[$j]} -eq 0 ]; then
		echo ${DEPTREE[$j]}
	fi
done
#--------------------------------------------------------------

#EOF
