#!/bin/bash
#==============================================================
#
#  Abs: Controls tmux sessions 
#
#  Name: tmux_session
#   $1 :  Session control statement (start,stop,open,restart)
#   $2 :  Script name
#   $3 :  MAX_ARRAY_BYTES for matlab or python argument
#
# ------------------------------------------------------------
# This script allows for tmux session management of different scripts
# and is designed to be run from the Matlab watchers EDM panel.
# ------------------------------------------------------------
#
#  Facility:  SLAC
#
#  Auth: 26-June-2018, J. Morad (jmorad)
#
#  Rev: 10-June-2020, P. Pascual (ppascual) 
#       Added matlab_version parameter for start/restart
#
#  Rev: 18-Sept-2018, G. Gregoric (ggreg)
#       Changed max_array_bytes parameter handling, added restart option, generalization
#
#  Rev: 08-Oct-2018, G. Gregoric (ggreg)
#       Support for multi-parameter matlab scripts, path to new Python_tmux_startup,
#       shorter delay when stop/restart
#
#==============================================================

help_message(){
    echo "Usage: $0 {start|stop|restart|open} matlab_script_name [matlab_version] [epics_ca_max_array_bytes] [params]"
    echo "       $0 {start|stop|restart|open} script_name.py [args]"
    exit 1
}

if [ "$#" -lt 2 ]; then
    help_message
fi


TMUX_CONF_PATH=$TOOLS/script/tmux.conf

SCRIPT_NAME=$2
MATLAB_SCRIPT_PATH=$TOOLS/matlab/scripts
PYTHON_SCRIPT_PATH=$TOOLS/script

SSH_USER=physics
SSH_SERVER=lcls-srv03

MAX_BYTES=0

if [[ $2 = *".py" ]]; then
    STARTUP_SCRIPT=$PYTHON_SCRIPT_PATH/Python_tmux_startup
    SCRIPT_SESSION_NAME=${2//./_}_$3
    EXIT_CMD="exit()"
    ARGS=${@:2}  
else
    CONTROL_CMD=$1
    SCRIPT_SESSION_NAME=$2
    MATLAB_VERSION=$3    
    ARGS=""

    if [[ "${4}" =~ ^[0-9]+$  ]]; then
        MAX_BYTES=$4
        echo "Setting EPICS_CA_MAX_ARRAY_BYTES = $MAX_BYTES"
        ARGS="$SCRIPT_SESSION_NAME ${@:5}"
    else
        ARGS="$SCRIPT_SESSION_NAME ${@:4}"
    fi

    STARTUP_SCRIPT="$MATLAB_SCRIPT_PATH/Matlab_tmux_startup -m ${MATLAB_VERSION}"
    EXIT_CMD="exit"
fi

echo "Session name: $SCRIPT_SESSION_NAME"

start(){
    ssh -t $SSH_USER@$SSH_SERVER " \
    if tmux has -t $SCRIPT_SESSION_NAME ;\
    then \
        echo \"##############################################\" ;\
        echo \"#   Warning! Session already exists!         #\" ;\
        echo \"#   New session NOT started.                 #\" ;\
        echo \"#   Please use the open button to connect.   #\" ;\
        echo \"##############################################\" ;\
        bash --noprofile --norc ;\
    else \
        echo \"Starting session...\" ;\
        tmux -f $TMUX_CONF_PATH new -d -s $SCRIPT_SESSION_NAME ;\
        if [ \"$MAX_BYTES\" -ne \"0\" ] ;\
        then \
            tmux send -t $SCRIPT_SESSION_NAME \"export EPICS_CA_MAX_ARRAY_BYTES=$MAX_BYTES \" ;\
            tmux send -t $SCRIPT_SESSION_NAME C-m ;\
        fi ;\
        tmux send -t $SCRIPT_SESSION_NAME \"$STARTUP_SCRIPT $ARGS\" ;\
        tmux send -t $SCRIPT_SESSION_NAME C-m ;\
        tmux attach -t $SCRIPT_SESSION_NAME ;\
    fi ;\
    "
}

stop(){
    ssh -t $SSH_USER@$SSH_SERVER " \
    echo \"Issuing exit command to session and waiting for 5 seconds...\" ;\
    tmux send -t $SCRIPT_SESSION_NAME \"$EXIT_CMD\" ;\
    tmux send -t $SCRIPT_SESSION_NAME C-m ;\
    sleep 5 ;\
    echo \"Issuing kill command to tmux session...\" ;\
    tmux kill-session -t $SCRIPT_SESSION_NAME ;\
    "
}

open(){
    ssh -t $SSH_USER@$SSH_SERVER " \
    echo \"Checking if session exists...\" ;\
    if tmux has -t $SCRIPT_SESSION_NAME ;\
    then \
        echo \"Found existing session, connecting...\" ;\
        tmux attach -t $SCRIPT_SESSION_NAME ;\
    else \
        echo \"######################################################\" ;\
        echo \"#   Warning! Session not found!                      #\" ;\
        echo \"#   Please verify that a session has been started.   #\" ;\
        echo \"######################################################\" ;\
        bash --noprofile --norc ;\
    fi ;\
    "
}

case "$1" in
    start)
        start
        ;; 
    stop)
        stop
        ;;
    open)
        open
        ;;
    restart)
        stop
        sleep 1
        start
        ;;
    *)
        help_message
esac

