#!/bin/sh

ROOT="....."

# If readlink -f works, compute ROOT automatically.
if FULLPATH=$(readlink -f -- "$0" 2>/dev/null); then
    ROOT=$(dirname "$FULLPATH")
# Otherwise require the user to hardcode ROOT by replacing '.....'
else
    if [ "$ROOT" = "....." ]; then
        echo "You must edit the 'magma' script and change the ..... at the" >&2
        echo "top of the file to the full pathname of the place where the" >&2
        echo "Magma files currently are." >&2
        exit 1
    fi
fi

# If MAGMA_CMD is not set, and readlink failed, set MAGMA_CMD to $0
export MAGMA_CMD=${MAGMA_CMD:-${FULLPATH:-$0}}


MAGMAPASSFILE="${MAGMAPASSFILE:-${ROOT}/magmapassfile}"
if [ ! -f "${MAGMAPASSFILE}" ] && [ -f "${MAGMAPASSFILE}.txt" ]; then
  MAGMAPASSFILE="${MAGMAPASSFILE}.txt"
fi
export MAGMAPASSFILE

export MAGMA_SYSTEM_SPEC="${MAGMA_SYSTEM_SPEC:-${ROOT}/package/spec}"

defpackroot=$(dirname "$MAGMA_SYSTEM_SPEC")
export MAGMA_SYSTEM_PACKAGE_ROOT="${MAGMA_SYSTEM_PACKAGE_ROOT:-$defpackroot}"

if [ "${MAGMA_STARTUP_FILE}" = "" ]; then
    if [ -f "${HOME}/.magmarc" ]; then
        MAGMA_STARTUP_FILE="${HOME}/.magmarc"
        export MAGMA_STARTUP_FILE
    fi
fi

export MAGMA_LIBRARY_ROOT="${MAGMA_LIBRARY_ROOT:-${ROOT}/libs}" 

export MAGMA_LIBRARIES="${MAGMA_LIBRARIES:-c9lattices:examples:galpols:intro:isolgps:matgps:pergps:simgps:solgps}"

export MAGMA_HELP_DIR="${MAGMA_HELP_DIR:-${ROOT}/InternalHelp}"

export MAGMA_HTML_DIR="${MAGMA_HTML_DIR:-${ROOT}/doc/html}"

if [ "$(uname)" = "Darwin" ]; then
    ulimit -s 16384
    BINARY="${ROOT}/bin/magma.exe"
elif [ "$(uname)" = "Linux" ]; then
    BINARY="${ROOT}/magma.exe"
    export MKL_SERIAL=YES
    export OMP_NUM_THREADS=1
    export OPENBLAS_NUM_THREADS=1
fi

if [ $# = 0 ]
then
    exec "${BINARY}"
else
    exec "${BINARY}" "$@"
fi
