#!/bin/sh

# Given a list of files, rewrite the non-system shared library
# dependencies of executables and libraries to be
# @executable_path/../lib/condor/... or @executable_path/../lib/...
# Other types of files are ignored.

if [ "$1" = "" ] ; then
  echo "Usage:" `basename $0` "<executable/library> ..."
  exit 1
fi
for filename in "$@" ; do
  type=`file -h $filename`
  if echo $type | grep -q -e 'dynamically linked shared library' -e 'executable' ; then
    basefile=`basename $filename`
    libraries=`otool -L $filename | grep -e '^[[:space:]][^@]' -e libssl -e libcrypto -e '@rpath/libSciTokens' |sed 's|^.\([^ ]*\) .*|\1|' | grep -v '^/usr/lib' | grep -v '^/System/' | grep -v '^/Library/' | grep -v "$basefile "`
    external_resolver="@executable_path/../lib/condor"
    internal_resolver="@executable_path/../lib"
    tool_args=""
    if echo $type | grep -q -e 'dynamically linked shared library' ; then
      tool_args="-id $basefile"
      if echo $filename | grep -q -e 'libcondor_utils' -e 'libpyclassad' -e 'libclassad' -e 'libchirp_client' -e 'libcondorapi' ; then
        external_resolver="@loader_path/condor"
        internal_resolver="@loader_path"
      else
        external_resolver="@loader_path"
        internal_resolver="@loader_path/.."
      fi
    fi
    if echo $filename | grep -q -e 'htcondor.*\.so' -e 'classad.*\.so' ; then
      external_resolver="@loader_path/../../condor"
      internal_resolver="@loader_path/../.."
    fi
    
    for lib in $libraries ; do
      baselib=`basename $lib`
      if echo $baselib | grep -q -e 'classad' -e 'condor' -e 'fmt'; then
        tool_args="$tool_args -change $lib $internal_resolver/$baselib"
      else
        tool_args="$tool_args -change $lib $external_resolver/$baselib"
      fi
    done
    if [ "$tool_args" != "" ] ; then
      install_name_tool $tool_args $filename
    fi
  fi
done
