#!/bin/sh
rtld=/usr/lib/ld-linux-armhf.so.3
filename_magic_regex="((^|/)lib|.so$)"
silent=0
result=1
file=$1

[ $# -gt 0 ] || {
  echo "Usage: ldd [-s] <file>"
  echo "Option: -s silent (do not print shared libraries only perform the check)"
  exit 1
}

case "$1" in
-s)
silent=1
shift
;
*)
;
esac

file=$1
case $file in
  */*) :
       ;
  *) file=./$file
     ;
esac

if [ ! -e $file ]; then
  echo "ldd: $file: No such file or directory" >&2
elif [ ! -f $file ]; then
  echo "ldd: $file: not regular file" >&2
elif [ -r $file ]; then
  if [ ! -x "$file" ] && eval echo "$file" \
  | grep -v "$filename_magic_regex" > /dev/null; then
  	echo "ldd: warning: you do not have execution permission for '$file'"
  fi    
  verify_out=
  list_out=
  trace_out=
  ret=0
  verify_out=$($rtld --verify "$file" 2>&1)
  [ $? = 0 ] || ret=$?
  [ $ret = 0 ] || { result=$ret; break; }
  list_out=$($rtld --list "$file" 2>&1)
  [ $? = 0 ] || ret=$?
  [ $ret = 0 ] || { result=$ret; break; }
  trace_out=$(LD_TRACE_LOADED_OBJECTS=1 $rtld "$file" 2>&1)  
  [ $ret = 0 ] || {
    [ $silent = 1 ] || echo "ldd: $rtld returned with exit code ($ret)" >&2  	
    [ -z "$verify_out" ] && [ $silent = 1 ] || echo "ldd: $verify_out" >&2
    [ -z "$list_out" ] && [ $silent = 1 ] || echo "ldd: $list_out" >&2
    [ -z "$trace_out" ] && [ $silent = 1 ] || echo "ldd: $trace_out" | tr '\t' ' ' >&2
    exit $result
  }
  [ $silent = 1 ] || {
    [ -z "$trace_out" ] || echo "ldd: $trace_out" | tr '\t' ' '
  }
  # If we reached here, everything went fine
  result=0
else
  echo "ldd: error: cannot read file '$file'" >&2
fi
	
exit $result