#!/bin/sh

if [ -z "$1" ]; then
    echo ""
    echo " Usage: nopathR <r-home>"
    echo ""
    exit 0
fi

R=$1

if [ ! -e $R/lib/libR.dylib ]; then
    echo "Cannot find $R/lib/libR.dylib"
    exit 1
fi

PWD=`pwd`

# it takes care of any linked libraries in /usr/local that are supplied
# (as for packages)

rlib=$R/lib
cd $R/
# now go through all so/dylibs we find
libs=`find . -name \*.so -or -name \*.dylib -or -name \*.jnilib`
for lib in $libs; do
    # in each so/dylib/jnilib, find dependent libraries beginning with /usr/local ot /opt
    lds=`otool -L $lib| sed -E -n 's:.(/opt/[^X].*|/usr/local/.*) [(]com.*:\1:p'`
    for ld in $lds; do
        # find out what the base name of the linked dylib is
	ldname=`basename $ld`
	if [ -e "$rlib/$ldname" ]; then
            # if a copy exists in the same location as libR.dylib, fix it
	    echo "LDI: $ld -> $rlib/$ldname"
	    install_name_tool -change "$ld" "$rlib/$ldname" $lib
	else
            # otherwise warn - that is an unresolved dependency
	    echo "LDW: WARNING: $ld not found in $rlib/$ldname"
	fi
    done
done

# fix permission issue with config.h
if [ -e $R/../PrivateHeaders ]; then
    chmod a+r $R/../PrivateHeaders/*
fi

echo "Done"

cd $PWD