#!/bin/bash

if [ -d /afs/slac/g/lcls ]; then
    export FACILITY_ROOT=/afs/slac/g/lcls
    export MLM_LICENSE_FILE="27010@license1,27010@license2,27010@license3"
elif [ ! -z "${FACILITY}" ]; then
    export FACILITY_ROOT=/usr/local/${FACILITY}
else
    export FACILITY_ROOT=/usr/local/lcls
fi

invokeMatlabSetup () {
    if [ "$1" = "2012a" ]; then
        if [ -f ${FACILITY_ROOT}/tools/oracle/oracleSetup.bash ]; then
            source ${FACILITY_ROOT}/tools/oracle/oracleSetup.bash
        fi

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

        export MATLAB_VER=2012a
        local EPICS_HOST_ARCH=linux-x86
        if [ -d /afs/slac/g/lcls ]; then 
            if [ -f ${FACILITY_ROOT}/epics/setup/fixed-epics-setup.bash ]; then
                source ${FACILITY_ROOT}/epics/setup/fixed-epics-setup.bash
                if [ -f ${FACILITY_ROOT}/epics/setup/epicsenv-3.14.12.bash ]; then
                    source ${FACILITY_ROOT}/epics/setup/epicsenv-3.14.12.bash
                fi
            fi

            if [ -f ${FACILITY_ROOT}/tools/matlab/setup/matlabSetup_dev.bash ]; then
                source ${FACILITY_ROOT}/tools/matlab/setup/matlabSetup_dev.bash
                export PATH=${MATLAB_ROOT}/bin:$PATH
            fi
        else
            if [ "${FACILITY}" = "lcls" ]; then
                if [ -f ${FACILITY_ROOT}/epics/setup/fixed-epics-setup.bash ]; then
                    source ${FACILITY_ROOT}/epics/setup/fixed-epics-setup.bash
                    if [ -f ${FACILITY_ROOT}/epics/setup/epicsenv-3.14.12.bash ]; then
                        source ${FACILITY_ROOT}/epics/setup/epicsenv-3.14.12.bash
                    fi
                fi

                if [ -f ${FACILITY_ROOT}/tools/matlab/setup/matlabSetup.bash ]; then
                    source ${FACILITY_ROOT}/tools/matlab/setup/matlabSetup.bash
                    export PATH=${MATLAB_ROOT}/bin:$PATH
                fi
            elif [ "${FACILITY}" = "facet" ]; then
            if [ -f ${FACILITY_ROOT}/epics/setup/epicsReset_facet.bash ]; then
                source ${FACILITY_ROOT}/epics/setup/epicsReset_facet.bash
                if [ -f ${FACILITY_ROOT}/epics/setup/epicsSetup_facet.bash ]; then
                    source ${FACILITY_ROOT}/epics/setup/epicsSetup_facet.bash
                fi
            fi

                if [ -f ${FACILITY_ROOT}/tools/matlab/setup/matlabSetup_facet.bash ]; then
                    source ${FACILITY_ROOT}/tools/matlab/setup/matlabSetup_facet.bash
                    export PATH=${MATLAB_ROOT}/bin:$PATH
                fi
            fi
        fi
    elif [ "$1" = "2019a" -o "$1" = "2020a" ]; then
        if [ -f ${FACILITY_ROOT}/tools/oracle/oracleSetup-R11.2.0.4.bash ]; then
            source ${FACILITY_ROOT}/tools/oracle/oracleSetup-R11.2.0.4.bash
        fi

        if [ -f ${FACILITY_ROOT}/physics/setup/javaSetup-R1.8.0_181.bash ]; then
            source ${FACILITY_ROOT}/physics/setup/javaSetup-R1.8.0_181.bash 2>&1 > /dev/null
        fi

         if [ -f ${FACILITY_ROOT}/epics/setup/epicsenv-7.0.2-1.1.bash ]; then
            source ${FACILITY_ROOT}/epics/setup/epicsenv-7.0.2-1.1.bash
         fi
        
        if [ "$1" = "2019a" ]; then
            export MATLAB_VER=2019a
        elif [ "$1" = "2020a" ]; then
            export MATLAB_VER=2020a
        fi
        
        if [ "${FACILITY}" = "lcls" -o "${FACILITY}" = "dev" ]; then 
            if [ -f ${FACILITY_ROOT}/tools/matlab/setup/matlabSetup64.bash ]; then
                source ${FACILITY_ROOT}/tools/matlab/setup/matlabSetup64.bash
            fi
        elif [ "${FACILITY}" = "facet" ]; then
            if [ -f ${FACILITY_ROOT}/tools/matlab/setup/matlabSetup64_facet.bash ]; then
                source ${FACILITY_ROOT}/tools/matlab/setup/matlabSetup64_facet.bash
            fi
        fi
    else
        echo "Invalid MATLAB version specified. Currently supported: 2012a, 2019a, 2020a"
        usage
    fi
    
    if [ -n "$2" ]; then 
        export EPICS_CA_MAX_ARRAY_BYTES="$2"
    fi
}

usage() {
    echo "Description: launcher script that sets up appropriate MATLAB environment."
    echo " "
    echo "Usage: `basename $0` [OPTIONS] [-r MATLAB_FUNCTION]"
    echo "    Default: not specifying [-r MATLAB_FUNCTION]"
    echo "             launches an instance of MATLAB ${MATLAB_VER}"
    echo " "
    echo "    Options:"
    echo "    -h | --help: print this usage info"
    echo "    --camaxbytes: override EPICS_CA_MAX_ARRAY_BYTES" 
    echo "                  environment variable."
    echo "                  Default: ${EPIC_CA_MAX_ARRAY_BYTES}"
    echo "    --nojvm: Run without invoking MATLAB JVM"
    echo "    -d | --desktop: Run MATLAB in desktop mode."
    echo "    -m | --matlab: Specify the version of MATLAB to run."
    echo "                   Currently supported: 2012a, 2019a, 2020a"
    echo "                   Default: ${MATLAB_VER}"
    echo "    -r: launch MATLAB and run MATLAB_FUNCTION."

    exit 1
}

OPTS=`getopt -o hdm:r: --long 'help,camaxbytes:,nojvm,desktop,matlab:' -- "$@"`

if [ "$?" -ne 0 ]; then
    echo "Incorrect options provided."
    usage
fi

eval set -- "$OPTS"

NOJVM=false
DESKTOP=false
MATLAB_REL="${MATLAB_VER}"
MATLAB_FUNC=""
CA_MAX_BYTES="${EPICS_CA_MAX_ARRAY_BYTES}"

while [ "$#" -gt 0 ]; do
    while true; do
        case $1 in 
            -h | --help) 
                usage
                break
                shift
                ;;
            --camaxbytes)
                CA_MAX_BYTES=$2
                shift 2
                ;;
            --nojvm)
                NOJVM=true
                shift
                ;;
            -d | --desktop)
                DESKTOP=true
                shift
                ;;
            -m | --matlab)
                MATLAB_REL=$2
                shift 2
                ;;
            --)
                shift
                break
                ;;
            *)
                break
                ;;
        esac
    done
    if [ ! -z "${MATLAB_FUNC}" ]; then
        MATLAB_FUNC="${MATLAB_FUNC} $1"
    else
        MATLAB_FUNC+=$1
    fi
    shift 
done

invokeMatlabSetup "${MATLAB_REL}" "${CA_MAX_BYTES}"

MATLAB_BASE_ARGS=( -nosplash -nodesktop )
if [ "${DESKTOP}" = true ]; then
    MATLAB_BASE_ARGS=( -nosplash -desktop )
fi

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

if [ "${MATLAB_REL}" = "2012a" ]; then
    MATLAB_BASE_ARGS+=( -glnx86 )
fi

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

# Create log filename
MATLAB_FUNC_LOG=$(echo -e ${MATLAB_FUNC} | sed -e 's/^-r //g' -e 's/^\"*\s*\([a-zA-Z0-9_]*\).*\"*$/\1/g')

if [ -z "${MATLAB_FUNC_LOG}" ]; then
    MATLAB_FUNC_LOG="MATLAB_${MATLAB_REL}"
fi

if [ -z "${PHYSICS_USER}" ]; then
    USER=`whoami`
else
    if [ "${PHYSICS_USER}" = "none" ]; then
        USER=`whoami`
    else
        USER="${PHYSICS_USER}"
    fi
fi

if [ "${USER}" = "softegr" ] ; then
    USER="${SOFTEGR_USER}"
    if [ "${SOFTEGR_USER}" = "none" ]; then
        USER=`whoami`
    else
        USER=${SOFTEGR_USER}
    fi
fi

DATE_STR=`date +"%Y-%b-%d_%T%z"`

if [ -d $MATLABDATAFILES/log ]; then
    LOG_FILE=$MATLABDATAFILES/log/${MATLAB_FUNC_LOG}-${USER}-${DATE_STR}-$HOSTNAME-$DISPLAY.log
else
    LOG_FILE=${MATLAB_FUNC_LOG}-${USER}-${DATE_STR}-$HOSTNAME-$DISPLAY.log
fi


MATLAB_ARGS_ARRAY=( "${MATLAB_BASE_ARGS[@]}" "${MATLAB_FUNC[@]}" )
MATLAB_ARGS_ARRAY+=( -logfile "${LOG_FILE}" )
`which matlab` "${MATLAB_ARGS_ARRAY[@]}"
