#!/bin/bash
#==============================================================
#  Name:  matlab_prelaunch_console.sh
#
#  Rem:   This script selects a prelaunched MATLAB session and launches a new one.
#
#  Usage: This script is called by pressing the "Text Matlab..." button from lclshome
#
#  Auth:  12-May-2017, Janos Vamosi (jvamosi)
#  Rev:   dd-mmm-yyyy, Whoever (user):
#
#--------------------------------------------------------------

# Get machine hostname
CHECK_HOST=`hostname`

# Uncomment for testing on lcls-dev2, pretend we are on "opi2"
#if [ "$CHECK_HOST" = "lcls-dev2" ] ; then
#    CHECK_HOST="opi2"
#fi

# Uncomment for testing on lcls-dev3, pretend we are on "opi3"
#if [ "$CHECK_HOST" = "lcls-dev3" ] ; then
#    CHECK_HOST="opi3"
#fi

# Check if machine is an OPI, and get OPI number
for i in `seq 1 50` ; do
    if [ "$CHECK_HOST" = "opi$i" ] ; then 
        export OPI_NUM=$i
        export AREA=ACR0
        break;
    fi
done

MATLABS_WAITING=0

# Check if on an OPI
if [ -n "$OPI_NUM" ] ; then
    # Check if there are waiting MATLAB sessions
    MATLABS_WAITING=`caget -t OPI:$AREA:$OPI_NUM:MATLABS_WAITING`
fi

if [ -n "$MATLABS_WAITING" ] && [ "$MATLABS_WAITING" -gt "0" ] ; then
# Launch MATLAB in background
    xterm -iconic -fn 10x20 -geometry 100x40 -T "Text MATLAB 2012a - DO NOT PRESS [X]" -e run_matlab.bash --matlab=2012a
else
# any other case launch MATLAB in foreground
    xterm -fn 10x20 -geometry 100x40 -fg lightgreen -bg black -e run_matlab.bash --matlab=2012a
fi

