#! /bin/sh
# get the framework name
fwname=$1
# get the directory of the framework
fwdir=$2
# get the application name
appname=$3

shift 3

# create the application dir name
appdir=$appname.app
# check if the framework is required and get the full name
old_installname=`otool -X -L $appdir/Contents/MacOS/$appname | grep -m 1 $fwname | cut -f 1 -d ' ' `
if test -z "$old_installname"; then
    exit -1
fi

# get the basename of the required framework
fwfile=`basename $old_installname`
# copy the required framework
if test ! -f $fwdir/$fwfile; then
    echo "$0: the required framework $fwdir/$fwfile cannot be found" 
    exit -1
fi
cp $fwdir/$fwfile $appdir/Contents/Frameworks/$fwfile

# change the executable path in the framework itself, then change the search path in the application
install_name_tool -id @executable_path/../Frameworks/$fwfile $appdir/Contents/Frameworks/$fwfile
install_name_tool -change $old_installname @executable_path/../Frameworks/$fwfile $appdir/Contents/MacOS/$appname

# the remaining arguments are other frameworks that depend on this framework.
# locate these frameworks in the bundle and change the search path for the new 
# framework, too.
for otherfwname in $*; do
    instname=`otool -X -L $appdir/Contents/MacOS/$appname | grep -m 1 $otherfwname | cut -f 1 -d ' ' `
    if test "$instname"; then
	otherfwfile=`basename $instname`
	if test -f $appdir/Contents/Frameworks/$otherfwfile; then
	    old_installname=`otool -X -L $appdir/Contents/Frameworks/$otherfwfile | grep -m 1 $fwfile | cut -f 1 -d ' '`
	    install_name_tool -change $old_installname @executable_path/../Frameworks/$fwfile $appdir/Contents/Frameworks/$otherfwfile
	fi
    fi
done
