#!/bin/sh
###############################################################################
##                                                                           ##
##                                 libDeps                                   ## 
##                                                                           ## 
## This little script searches for all libraries needed by file $1           ##
## and copies them together with symbolic link names to $2 ($2)              ##
##                                                                           ##   
## Usage: libDeps BINARY LIBDIR                                              ##
##        where LIBDIR is the directory where all the libs will be copied    ##
##                                                                           ##
##                                                                           ##
## copylefted by Timo Benk <t_benk@users.sourceforge.net>                    ##
##                                                                           ##
###############################################################################


if [ ! "$1" ]; then
cat <<EOF
Usage: $0 BINARY LIBDIR
This script copies all libraries needed by BINARY to LIBDIR
EOF
  exit 1
elif [ ! "$2" ]; then
cat <<EOF
Usage: $0 BINARY LIBDIR
This script copies all libraries needed by BINARY to LIBDIR
EOF
    exit 1
fi

# resolves the symlink $1 and put it into $SYMLINKTARGET, if $1 is not
# a symlink it will put $1 in $SYMLINKTARGET
resolveSymLink() {
    if test -L $1; then
        # get link target ...
	SYMLINKTARGET=`ls -l $1 | cut -d \> -f 2 | cut -b2-`
        # ... and look if it's absolute or relative
	if [ `basename $SYMLINKTARGET` = $SYMLINKTARGET ]; then
            # put the path before the name so that we can copy the library
	    SYMLINKTARGET=${1%/*}/$SYMLINKTARGET
        fi
    else
	SYMLINKTARGET=$1
    fi
}
    

LIBDIR="$2"
BINARY="$1"

echo -n "I'm searching, that will take some time so be patient ... "
LIBS=`ldd $BINARY 2> /dev/null | grep =\> | cut -d \> -f 2 | cut -d \( -f 1 | sort | uniq`
NOTFOUND=`ldd $BINARY 2> /dev/null | grep not\ found | cut -d = -f 1 | sort | uniq`

for i in $LIBS; do
    # if it is a symbolic link
    # we don't want to copy any symlinks 'cause they will be rebuild
    # by ldconfig later
    resolveSymLink $i
    ALLABSLIBS="$ALLABSLIBS $SYMLINKTARGET"
done
    

# That's it, now copy it to $LIBDIR
cp -d $ALLABSLIBS $LIBDIR 

# These libraries can't be found
echo $NOTFOUND