#!/usr/bin/bash
##
## Non-recursive / Simple output ldd(1)
## Copyright (C) 2018 SATOH Fumiyasu @ OSSTech Corp., Japan
##               <https://www.OSSTech.co.jp/>
##               <https://fumiyas.github.io/>
##
## License: GNU General Public License version 3
##

set -u

export LC_ALL="C"
export PATH="/bin:/usr/bin"

escape_meta()
{
  sed 's/[^a-zA-Z0-9_\-]/\\&/g'
}

## ======================================================================

## Set options for GNU by default
file_opts='-L'
file_libexec_re=' (executable|shared object|dynamic lib)[, ]'
objdump='objdump'

case $(uname) in
SunOS)
  file_opts=''
  objdump='gobjdump'
  export PATH="$PATH:/usr/sfw/bin"
  ;;
esac

## ======================================================================

for obj in "$@"; do
  echo "$obj needs:"
  if file $file_opts "$obj" |grep -E "$file_libexec_re" >/dev/null; then
    :
  else
    echo $'\tnot a dynamic executable'
    continue
  fi
  lib_names_pattern=$(
    "$objdump" -p "$obj" \
    |sed -n '/^Dynamic Section:/,/^$/s/^ *NEEDED *//p' \
    |escape_meta \
    |escape_meta \
    |xargs \
    |sed 's/ /|/g' \
    ;
  )

  ldd "$obj" \
  |sed -n \
    -e 's|lib[^ ]* =>[^/]*/|/|p' \
  |sed \
    -e 's| (0x[0-9a-f]*)||' \
    -e 's|/\{2,\}|/|g' \
  |grep -E "/($lib_names_pattern)$" \
  |sort \
  ;
done

exit 0
