#!/bin/bash -x
#norc
#==============================================================
#
#  Abs:  Starts  Matlab scripts
#
#  Name: Mpsgui_server_facet_startup
#
#
# ------------------------------------------------------------
# This script gets called from facethome which performs an
# SSH call to facet-srv02 and sets it's display to the
# Virtual frame buffer (XVFB) before launching this script.
# ------------------------------------------------------------
#
#  Facility:  SLAC
#
#  Auth: 18-NOV-2015, Bianchini
#         
# Mod 
#
# 12-Sep-2018 Thomas Kurty
#  Copying script from LCLS for FACET-II
#
# 29-Aug-2016 Carolina Bianchini
#  Changed mps release version for launching the script.
#  Updated the log processing.
#
# 18-Nov-2015 Carolina Bianchini
#  Set MPSGUI_SERVER_STARTUP_SCRIPT & MPSGUI_SERVER_LOG_FILE_NAME.
#
#
#==============================================================
#
# Make sure physics is running the script on facet-srv02
#

if  ! [ "$USER" = "fphysics" ] && [ `uname -n` = "facet-srv02" ]
  then
     echo ""
     echo "This script must be run from the fphysics account"
     echo "on facet-srv02 - Preferably from facethome"
     echo ""
     exit
fi

# Set the display
#
OLD_DISP=`echo $DISPLAY`
export DISPLAY=:1.0

# 
# Setup LCLS Environment
#
#  if [ -e ${LCLS_ROOT}/tools/matlab/setup/matlabSetup.bash ]; then
#     . ${LCLS_ROOT}/tools/matlab/setup/matlabSetup.bash


##
# Start the MPSGUI_SERVER script
# 
#First: It is checking if it is already up and running
#Second: If it is not already running than it is starting it.
##
     MPSGUISERVERCOUNT=$(ps awwx |grep "mpsgui_server-FACET" | grep -v "grep" |grep -v "mpsgui_server_startup_facet" | wc -l)
     if [ "${MPSGUISERVERCOUNT}" -gt 1 ]; then
        echo "mpsgui server is already up and running"
    else
	#
        # Log file on nfs -name definition
        #
        if [ -e $PHYSICS_DATA/log/mpsgui_server ]; then
          log_file=$PHYSICS_DATA/log/mpsgui_server/mpsgui_server.log
        else
          log_file=mpsgui_server.log
        fi
	#The following command is moving the log file to a new one with date at the end of the file name
        MDATE=`date '+%e_%b_%Y_%H_%M'`
        if [ -e $log_file ]; then
          /bin/mv -f ${log_file} ${log_file}-$MDATE
        fi
	#the following command is starting mpsgui server
        #xterm -e  $PHYSICS_TOP/mpsgui/mpsgui_server-FACET &>> ${log_file} &
	cd $PHYSICS_TOP/mpsgui/
	./mpsgui_server-FACET &>> ${log_file} &
	sleep 1
        export DISPLAY=$OLD_DISP
        #xterm -e tail -f $log_file &
    fi
    #
    # log file cleanup -keep 5 log files
    #
    LOGCNT=`ls -t $PHYSICS_DATA/log/mpsgui_server/mpsgui_server.log* | wc -l`
    if [ "$LOGCNT" -gt 5 ]; then
        y=`expr $LOGCNT - 5`
        for x in `ls -t  $PHYSICS_DATA/log/mpsgui_server/mpsgui_server.log* | tail -n$y`
        do
          /bin/rm -f $x
        done
    fi
 #else
 #  echo "Sorry, can't find LCLS environment setup"
 # fi
