#!/bin/sh
# By: john@stilen.com
# Purpose: 
#  Ash scirpt to traverse shared library dependenceis of a list of binaries,
#  report the list, number of libs, and size sum of all libs.
#  used for memory resource allocation accounting.
echo "File:$1"
usage()
{
    echo "Usage: $0 <full path to file>
    Will build list of dependent libraries"
}
if [ -z "$1" ]; then
    usage;
    exit;
else
    BINS="${1}"
fi
if [ -f "${BIN}" ]; then
    echo "File does not exist: ${BIN}";
    usage;
    exit 1;
fi

Raw_LDD_List=`ldd $BINS 2> /dev/null \
| sed -n -e '/:$/ d; s/\t//;
 /^not a dynamic executable/ d;
 /^ldd:|ld-linux.so\|linux-gate.so/ d;
 s/^[^ ]\+ => \([^ ]\+\).*/\1/ p' \
| sort -ui |grep -v '^not'`

Almost_LDD_List=`ldd $Raw_LDD_List 2> /dev/null \
| sed -n -e '/:$/ d; s/\t//;
 /^not a dynamic executable/ d;
 /^ldd:|ld-linux.so\|linux-gate.so/ d;
 s/^[^ ]\+ => \([^ ]\+\).*/\1/ p' \
| sort -ui`

Final_LDD_List="$Raw_LDD_List $Almost_LDD_List"

count=`echo $Almost_LDD_List |wc -w`
new_count=0

while [ $count -ne $new_count ]; do
  #debug#echo "count=$count"
  count=$new_count
  Almost_LDD_List=`ldd $Almost_LDD_List 2> /dev/null \
   | sed -n -e '/:$/ d; s/\t//;
    /^not a dynamic executable/ d;
    /^ldd:|ld-linux.so\|linux-gate.so/ d;
    s/^[^ ]\+ => \([^ ]\+\).*/\1/ p' \
   | sort -ui`
  new_count=`echo $Almost_LDD_List |wc -w`
  Final_LDD_List="$Final_LDD_List $Almost_LDD_List"
done

Expanded_LDD_List=''
for dep in $Final_LDD_List; do
   # Add this dependency to the list
   Expanded_LDD_List="$Expanded_LDD_List $dep"
   # While this dependency is a link, recurse (until we hit a real file)
   while [ -L $dep ]; do
     # Find what the link points to
     dep_new=`readlink $dep`
     # Since many links are reliative, find the base dir
     prefix=`echo $dep |sed 's/\(.*\)\/.*$/\1/'`
     # Set $dep to the fully qualified path to what link points to
     dep=$prefix/$dep_new
     # Add this to the $Final
     Expanded_LDD_List="$Expanded_LDD_List $dep"
   done
done

Final_LDD_List="$Final_LDD_List $Expanded_LDD_List"
File_Count=$(echo $Final_LDD_List |wc -w)

echo "$Final_LDD_List"

Size=0
Count=0

for i in $Final_LDD_List; do
  if [ ! $(readlink $i) ]; then
    let Size=$Size+$(du "$i" |awk '{print $1}')
    let Count=$Count+1
  fi
done

echo -e "Result:
Number of All Libs:$File_Count
Number of unique Libs:$Count,
Total Lib Size:$Size"
