#!/bin/bash

if [ -d /afs/slac/g/lcls ]; then
    export LCLS_ROOT=/afs/slac/g/lcls
else
    export LCLS_ROOT=/usr/local/lcls
fi

if [ -f ${LCLS_ROOT}/tools/oracle/oracleSetup.bash ]; then
    source ${LCLS_ROOT}/tools/oracle/oracleSetup.bash
fi
if [ -f ${LCLS_ROOT}/physics/setup/javaSetup.bash ]; then
    source ${LCLS_ROOT}/physics/setup/javaSetup.bash 2>&1 > /dev/null
fi

if [ -f ${LCLS_ROOT}/epics/setup/fixed-epics-setup.bash ]; then
    source ${LCLS_ROOT}/epics/setup/fixed-epics-setup.bash
    if [ -f ${LCLS_ROOT}/epics/setup/epicsenv-3.14.12.bash ]; then
        source ${LCLS_ROOT}/epics/setup/epicsenv-3.14.12.bash
    fi
fi


invokeMatlabSetup() {
    export MATLAB_VER=2012a
    local EPICS_HOST_ARCH=linux-x86
    if [ -f ${LCLS_ROOT}/tools/matlab/setup/matlabSetup.bash ]; then
        source ${LCLS_ROOT}/tools/matlab/setup/matlabSetup.bash
    fi
}

invokeMatlabSetup

usage() {
    echo "Usage: `basename $0` [OPTIONS] -r MATLAB_FUNCTION"
    echo "    Options:"
    echo "    -h | --help: print this usage info"
    echo "    --nojvm: Run without invoking MATLAB JVM"

    exit 1
}

OPTS=`getopt -o hr: --long help,nojvm -- "$@"`

eval set -- "$OPTS"

NOJVM=false
MATLAB_FUNC=""

while [ "$#" -gt 0 ]; do
    while true; do
        case $1 in 
            -h | --help) 
                usage
                break
                ;;
            --nojvm)
                NOJVM=true
                shift
                ;;
            --)
                shift
                break
                ;;
            *)
                break
                ;;
        esac
    done
    MATLAB_FUNC="${MATLAB_FUNC} $1"
    shift
done

MATLAB_BASE_ARGS=( -glnx86 -nosplash -nodesktop )
if [ "${NOJVM}" = true ]; then
    MATLAB_BASE_ARGS+=( -nojvm )
fi

MATLAB_FUNC="${MATLAB_FUNC/\"/\'}"
MATLAB_FUNC="${MATLAB_FUNC/-r/-r \"}\""
MATLAB_FUNC="$(echo -e "${MATLAB_FUNC}" | sed -e 's/-r \" \(\S*\) \"/-r \"\1\"/g')"

# Create log file
MATLAB_FUNC_LOG=$(echo -e ${MATLAB_FUNC} | sed -e 's/-r \"\(\S*\)(.*)\"$/\1/g')

date=`date +"%a %b %e %T.%3N %Z %Y"`
year=`echo $date | cut -d" " -f6`-
month=`echo $date | cut -d" " -f2`-
day=`echo $date | cut -d" " -f3`-
time=`echo $date | cut -d" " -f4 | cut -c1-12`

if [ -e $MATLABDATAFILES/log ]; then
    LOG_FILE=$MATLABDATAFILES/log/${MATLAB_FUNC_LOG}-$user-$year$month$day$time-$HOSTNAME-$DISPLAY.log
else
    LOG_FILE=${MATLAB_FUNC_LOG}-$user-$year$month$day$time-$HOSTNAME-$DISPLAY.log
fi

echo "LOG_FILE = ${LOG_FILE}"

MATLAB_ARGS_ARRAY=( "${MATLAB_BASE_ARGS[@]}" "${MATLAB_FUNC[@]}" )
MATLAB_ARGS_ARRAY+=( -logfile "${LOG_FILE}" )
echo "Running: /usr/local/matlab/2012a/bin/matlab ${MATLAB_ARGS_ARRAY[@]}"
/usr/local/matlab/2012a/bin/matlab "${MATLAB_ARGS_ARRAY[@]}"
