#!/bin/bash -norc
#==============================================================
#       
#  Abs:  Starts Matlab 2019a GUIs from a PyDM shell command button 
#        push
#           
#  Name: MatlabGUI.2019a
#  Facility:  SLAC
#
#  Auth: 21-Oct-2019, Patrick Pascual (ppascual)
#
#  Rev: 
#==============================================================

if [ -d /afs/slac/g/lcls ]; then
    export LCLS_ROOT=/afs/slac/g/lcls
    # set license file for Dev environment
    export MLM_LICENSE_FILE="27010@license1,27010@license2,27010@license3"
else
    export LCLS_ROOT=/usr/local/lcls
fi

if [ -z $PHYSICS_USER ]
then
    user=`whoami`
else
    if [ none = $PHYSICS_USER ]
    then
        user=`whoami`
    else
        user=$PHYSICS_USER
    fi
fi

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`

GUI_NAME=$1

if [ -e $MATLABDATAFILES/log ]; then
    log_file=$MATLABDATAFILES/log/$GUI_NAME-$user-$year$month$day$time-$HOSTNAME-$DISPLAY.log
else
    log_file=$GUI_NAMEGUI-$user-$year$month$day$time-$HOSTNAME-$DISPLAY.log
fi
echo $GUI_NAME $log_file

echo "Starting new Matlab session"

if [ -f $TOOLS/oracle/oracleSetup-R11.2.0.4.bash ]; then
    source $TOOLS/oracle/oracleSetup-R11.2.0.4.bash
fi

if [ -f $PHYSICS_TOP/setup/javaSetup-R1.8.0_181.bash ]; then
    source $PHYSICS_TOP/setup/javaSetup-R1.8.0_181.bash
fi

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

invokeMatlabSetup() {
    export MATLAB_VER=2019a
    local EPICS_HOST_ARCH=rhel6-x86_64
    if [ -f $TOOLS/matlab/setup/matlabSetup64.bash ]; then
        source $TOOLS/matlab/setup/matlabSetup64.bash
    fi
} 

invokeMatlabSetup

# Don't pass GUI name if running MATLAB standalone
if [ "$GUI_NAME" = "matlab_2019a" ]; then
    GUI_NAME=""
fi

$PACKAGE_TOP/matlab/2019a/bin/matlab -nosplash -nodesktop -r startLCLS,$GUI_NAME -logfile $log_file
