#!/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#([@]executable_path/([^ ]+))#) {
      # remove @executable_path from the references

      print "chmod a+w '$i'\n";
      print "install_name_tool -change $1 $2 '$i'\n";
    }
    if(m#(/Users/.*/(lib/([^ /]+)))#) {
      # add missing libs and make references relative

      print "cp $1 build/lib/$3\n";
      print "chmod a+w build/lib/$3 '$i'\n";
      print "install_name_tool -change $1 $2 '$i'\n";
    }
  '
done | bash -
