#!/bin/bash

myreadlink () {
    (
	tfile=$1
	cd $(dirname "$tfile")
	tfile=$(basename "$tfile")
	while [ -L "$tfile" ]
	do
	    tfile=$(readlink "$tfile")
	    cd $(dirname "$tfile")
	    tfile=$(basename "$tfile")
	done
	pdir=$(pwd -P)
	echo "$pdir/$tfile"
    )
}

cmd=$(myreadlink "$0")
DIR=$(myreadlink $(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

## this is the system path for libPng.dylib needed by grDevices.so
## when loadlib libR.dylib using rgeneric.
pathA="/System/Library/Frameworks/ImageIO.framework/Versions/A/Resources"
pathB="/System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries"
LIBPNGPATH=$pathA:$pathB

for f in $DIR/first/lib*.dylib*; do
    case $f in
	$DIR/first/libjemalloc*.dylib*)
	    ##export DYLD_INSERT_LIBRARIES=$f
	    ##export DYLD_FORCE_FLAT_NAMESPACE=1
	    ;;
    esac
done

export DYLD_LIBRARY_PATH="$DIR/first:$RHOME_LIB:$DIR:$LIBPNGPATH:/usr/lib:/usr/local/lib:/opt/local/lib:$DYLD_LIBRARY_PATH"
if [ "${INLA_DEBUG}XX" != "XX" ]; then
    echo "DYLD_INSERT_LIBRARIES=$DYLD_INSERT_LIBRARIES"
    echo "DYLD_FORCE_FLAT_NAMESPACE=$DYLD_FORCE_FLAT_NAMESPACE"
    echo "DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH"
    ##export DYLD_PRINT_OPTS="1"
    ##export DYLD_PRINT_ENV="1"
    export DYLD_PRINT_LIBRARIES="1"
    ##export DYLD_PRINT_LIBRARIES_POST_LAUNCH="1"
    ##export DYLD_PRINT_APIS="1"
    ##export DYLD_PRINT_BINDINGS="1"
    ##export DYLD_PRINT_INITIALIZERS="1"
    ##export DYLD_PRINT_REBASINGS="1"
    ##export DYLD_PRINT_SEGMENTS="1"
    ##export DYLD_PRINT_STATISTICS="1"
    ##export DYLD_PRINT_DOFS="1"
    ##export DYLD_PRINT_RPATHS="1"
fi

export PARDISOLICMESSAGE=1
export OMP_NESTED=TRUE

## set default levels for nested openmp
nt="-t0:1"
for arg in "$@"; do 
    case "$arg" in
	-t*) nt="$arg";;
    esac
done
eval $("$DIR/$prog" $nt -mopenmp|grep ^export)
if [ ! -z ${INLA_DEBUG+x} ]; then
    set | grep ^OMP_ | while read v; do echo "*** $0 *** $v"; done
    echo " *** $0 *** exec $DIR/$prog $@"
fi

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