#!/bin/bash

TARGETDIR=$1

# process dependencies and their exact locations of all libs

cd $TARGETDIR

for i in `find . -name "*.dylib" -or -name "*.so"`
do
  otool -L $i | perl -ne '
    if(m#/'`basename $i`' #) {
      # skip references to self

      next;
    }

    if(m#(/usr/local/lib/([^ /]+))#) {
      # make reference to /usr/local/lib/* local

      print "# Reference to $1 found in '$i'\n";
      print "chmod a+w '$i'\n";
      print "install_name_tool -change $1 \@executable_path/../Frameworks/$2 '$i'\n";
    }

    if(m#(/opt/local/lib/([^ /]+))#) {
      # make reference to /opt/local/lib/* local

      print "# Reference to $1 found in '$i'\n";
      print "chmod a+w '$i'\n";
      print "install_name_tool -change $1 \@executable_path/../Frameworks/$2 '$i'\n";
    }
  '
done
