#!/bb/ash
# (c) Robert Shingledecker 2012
. /etc/init.d/tc-functions



TCEDIR=/etc/sysconfig/tcedir
BUILD=`getBuild`
if [ "$BUILD" == "x86" ]; then
	DEBBUILD="i386"
elif [ "$BUILD" == "armv7" ]; then
	DEBBUILD="armhf"
fi

getDeps1() {
> /tmp/"$1".pkglist
grep -B 1 -A 8 "^Package: $1$" "$DEBINX" |  grep -B8 "^$" > /tmp/"$1".pkglist
DEBINX=/tmp/"$1".pkglist
getDeps2 $1
#grep "^Depends:" /tmp/"$1".pkglist | cut -f2 -d":" | tr -d ',' | tr -d '|'
#grep "^Filename:" /tmp/"$1".pkglist | cut -f2 -d":" | tr -d ' ' > /tmp/work/"$1"
rm /tmp/"$1".pkglist
}

getDeps2() {
	awk -v package="Package: $1" -v build="$DEBBUILD" -v location="/tmp/work/$1" '
	BEGIN {
		RS=""
		FS="\n"
	}
	{
		if ($1 == package) {
			for (i=2; i <= NF; i++) {
				split($i,f,": ")
			
		
				if ( f[1] == "Architecture" ) {
					if ( f[2] == "all" )
						{}
					else if ( f[2] == build )
						{}
					else
						break
					}
			


				if ( f[1] == "Depends" ) {
					jmax = split(f[2],item,",")
					for (j=1; j<=jmax; j++) { 
						kmax = split(item[j],deps," ")
						print( deps[1] )
					}
				}
				if ( f[1] == "Filename" )
					print f[2] > location
						     
			
		}


		}
		
	} ' < "$DEBINX"


}

if [ -z "$1" ]
then
	echo "you must specify a search target."
	exit 1
fi
if ls -A /opt/debextra > /dev/null 2>&1; then

  if grep "^Package: "$1"$" "$TCEDIR"/debinx.* > /dev/null; then
    DEBINX=`grep -l "^Package: $1$" "$TCEDIR"/debinx.* | head -n 1`
    DEPS="$(getDeps2 $1)"
    #[ ! -z "$DEPS" ] && echo " "
    echo "$DEPS"
    exit
  else
    read DEBINX < /tmp/debinx
    DEBINX="/etc/sysconfig/tcedir/$DEBINX"
    DEPS="$(getDeps1 $1)"
    [ -z "$DEPS" ] && exit 1
    echo "$DEPS"
  fi
  

else
    read DEBINX < /tmp/debinx
    DEBINX="/etc/sysconfig/tcedir/$DEBINX"
    DEPS="$(getDeps1 $1)"
    [ -z "$DEPS" ] && exit 1
    echo "$DEPS"
fi

