#!/bin/bash

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

if [ -n "${INLA_MALLOC_LIB}" ]; then
    if [ -f "${INLA_MALLOC_LIB}" ]; then
	export DYLD_INSERT_LIBRARIES="${INLA_MALLOC_LIB}:$DYLD_INSERT_LIBRARIES"
	export DYLD_FORCE_FLAT_NAMESPACE=1
    else   
	for nm in ${INLA_MALLOC_LIB}; do
	    for f in $DIR/malloc/lib*.dylib*; do
		case "$f" in
		    $DIR/malloc/lib${INLA_MALLOC_LIB}malloc*.dylib)
			if [ -n "$DYLD_INSERT_LIBRARIES" ]; then
			    export DYLD_INSERT_LIBRARIES="$f:$DYLD_INSERT_LIBRARIES"
			else
			    export DYLD_INSERT_LIBRARIES="$f"
			fi
			export DYLD_FORCE_FLAT_NAMESPACE=1
			;;
		esac
	    done
	done
    fi
    case "$DYLD_INSERT_LIBRARIES" in
	*libjemalloc*.dylib) 
	    export MALLOC_CONF='abort_conf:true,metadata_thp:always'
	    ;;
    esac
fi

export OMP_SCHEDULE=STATIC
##export OMP_PROC_BIND=FALSE
##export OMP_WAIT_POLICY=ACTIVE
export PARDISOLICMESSAGE=1
export DYLD_LIBRARY_PATH="$DIR/first:$RHOME_LIB:$DIR:/usr/lib:/opt/homebrew/lib:$DYLD_LIBRARY_PATH"

if [ "${INLA_DEBUG}XX" != "XX" ]; then
    echo "MALLOC_CONF=$MALLOC_CONF"
    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"

    p="/usr/bin/sw_vers"
    test -x $p && $p
fi

export PARDISOLICMESSAGE=1
nt="-t$(sysctl -n hw.ncpu):1"
for arg in "$@"; do 
    case "$arg" in
	-t*) nt="$arg";;
    esac
done
eval $(echo $nt | awk -F: '{gsub(/^-t/,""); nt=1*$2; if (nt==0) nt=1; print "export OMP_NUM_THREADS=" $1 "," nt ";"; al=1; if(nt>1) al=2; print "export OMP_MAX_ACTIVE_LEVELS=" al ";"}')
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" "$@"
