#!/bin/bash

readlink -f / 2>/dev/null >/dev/null || \
    readlink () {
	(
	    shift 1
	    tfile=$1
	    cd $(dirname "$tfile")
	    tfile=$(basename "$tfile")
	    while [ -L "$tfile" ]
	    do
		tfile=$(readlink -f "$tfile")
		cd $(dirname "$tfile")
		tfile=$(basename "$tfile")
	    done
	    pdir=$(pwd -P)
	    echo "$pdir/$tfile"
	)
    }

cmd=$(readlink -f "$0")
DIR=$(dirname "$cmd")
tmp=$(basename "$cmd")
prog=${tmp%%.run}

if [ -z "$INLA_RHOME" ]; then
    if $(which R 2>/dev/null >/dev/null); then
	RHOME_LIB="$(R RHOME)/lib"
    else
	RHOME_LIB="/Library/Frameworks/R.framework/Resources/lib"
    fi
else
    RHOME_LIB="$INLA_RHOME/lib"
fi

export DYLD_LIBRARY_PATH="$RHOME_LIB:$DIR:/usr/lib:/usr/local/lib:/opt/local/lib:$DYLD_LIBRARY_PATH"
if [ "${INLA_DEBUG}XX" != "XX" ]; then
    echo "DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH"
    otool -L "$DIR/$prog"
    export DYLD_PRINT_LIBRARIES=YES
fi

exec "$DIR/$prog" "$@"
