#!/bin/bash

# Find out which packages are depended upon by the .so files of the
# given package.  Note that instead of ldd, we use "nm -D" to find
# undefined symbols, which is much slower but should be more accurate.

PACKAGE="$1"
SHLIBS="`dpkg -L "$PACKAGE" | grep '\.so$'`"
BINARIES="`dpkg -L "$PACKAGE" | grep '/bin/'`"
UNDEF_SYMS=""
DEPENDED_PKGS=""

for file in $SHLIBS $BINARIES ; do
	UNDEF_SYMS="`echo "$UNDEF_SYMS" ; \
		nm -D $file 2> /dev/null | grep ' U ' | awk '{print $2}'`"
done

UNDEF_SYMS="`echo "$UNDEF_SYMS" | sort | uniq`"

# prepare table of symbols defined in each library

ALL_LIBS="`echo /lib/*.so /usr/lib/*.so /usr/X11R6/lib/*.so`"

if [ ! -f $HOME/.shlibs-database ] ; then
	echo "Preparing table of defined symbols..."
	for lib in $ALL_LIBS ; do
		nm -D $lib 2> /dev/null | egrep ' [ABDGRSTVW] ' | \
			awk '{print "'$lib' " $3}' >> $HOME/.shlibs-database
	done
fi

echo
echo "Searching for libraries defining symbols needed by package $PACKAGE:"

for sym in $UNDEF_SYMS ; do
	symresults=""
	echo $sym
	for lib in `grep ' '$sym'$' $HOME/.shlibs-database | awk '{print $1}'`
	do
		pkgresult="`dpkg -S $lib 2> /dev/null`"
		if [ -n "$pkgresult" ] ; then
			echo "     => $pkgresult"
			DEPENDED_PKGS="`echo "$DEPENDED_PKGS" ; \
			echo "$pkgresult" | awk '{print $1}' | tr -d ':'`"
			symresults=true
		fi
	done
	[ -z "$symresults" ] && NONEXISTENT="`echo "$NONEXISTENT" ; echo $sym`"
done

DEPENDED_PKGS="`echo "$DEPENDED_PKGS" | sed 's/^libc6$/libc6-dev/' | \
	sort | uniq | grep -v '^'$PACKAGE'$'`"

echo
echo "Library dependencies of $PACKAGE:"
echo "$DEPENDED_PKGS"

if [ -n "$NONEXISTENT" ] ; then
	echo
	echo "*** Could not find the following symbols in any library:"
	echo "$NONEXISTENT"
fi

exit 0

