#!/bin/bash
#==============================================================
#  Name:  cudControl
#
#  Rem:   This script launches CUD displays on named CUD monitors.
#           It uses an edmFilter to call the script cud2edl to 
#           determine the L/R location for .cud files.
# 
#  Usage: cudControl action groupSet Display
#         action: one of "localDisp", "create", "kill" or "print"
#         groupSet: 1 or 2 (1st or second group of 16 CUD monitors)
#          
#  Auth:  05-Oct-2008, William Colocho (colocho)
#  Rev:   dd-mmm-yyyy,  Whoever    (user):
#  Rev:   25-05-2015,  Danielle  (sanzone):
#==============================================================

ACTION=$1
SET=$2
ROOM=$3
monitor=`caget -t CUD:${ROOM}0:$SET:DISPLAY` 
LorR=`echo $monitor | cut -d" " -f2`
#monitor=`echo ${monitor%% *} | tr [:upper:] [:lower:]`
monitor=`echo ${monitor%% *} | tr "A-Z" "a-z"`     
dispRval=`caget -t CUD:${ROOM}0:$SET:DISPLAY.RVAL`
typeRval=`caget -t CUD:${ROOM}0:$SET:TYPE.RVAL`
fileName=`caget -t CUD:${ROOM}0:$SET:FILENAME${typeRval}`
fileExtn=`echo ${fileName#*.}`
cudType=`caget -t CUD:${ROOM}0:$SET:TYPE`
infoPv="CUD:${ROOM}0:$SET:INFOSTR${dispRval}"
psFileName="/tmp/cudDisplay.ps"

#Figure out DISPLAY value from MONITOR name and Display input ($3)
display=`cat /usr/local/admin/sunray/${monitor}`

fileNameRoot=`echo $fileName | cut -f1 -d"."`
#if [ `echo $fileName | grep fastbpm` ]; then
#    echo Note: Using EPICS 3-14-8-2-lcls6_p1 for $fileName
#    source /usr/local/lcls/epics/setup/go_epics_3-14-8-2-lcls6_p1.bash
#fi

case $fileExtn in
  cud)
	CMD="edm"
	MODE="-x -noedit -noautomsg"
#        INLIST=`echo ${ACCLIST} | grep ${USER}`     #nobody should edit a .cud file, there's no way to put it in CVS.
#	if [ -n "${INLIST}" ]; then  
#	    MODE="-x -noedit -noautomsg"
#	fi
#

##  Note for cuds: note LorR variable doesn't get used here, the way the cud location gets launched is with the script cud2edl, which is called by the "edm" command with an edmFilter (see $TOOLS/EDM/config/edmFilters) when files with the .cud extension are launched.  
	;;

  edl)
	CMD="edm"
	MODE="-x -noedit -noautomsg"
#        INLIST=`echo ${ACCLIST} | grep ${USER}`     #no edit mode for everybody
#	if [ -n "${INLIST}" ]; then  
#	    MODE="-x -noedit -noautomsg"
#	fi
#
	;;
  m)
        CMD="matlab -nodesktop"
	;;
  stp)
        CMD="StripTool"
	;;
  hla)                                             #"high level apps" LandR doesn't work
	CMD="/usr/local/lcls/tools/script/HLAWrap"
	fileName=`echo $fileName | cut -d. -f1`
	fileName="$PHYSICS_TOP/$fileName -DCUD=$SET -Ddisplay.location=$LorR"
	;;
  *)
	echo "Sorry don't understand ${ACTION}"
	;;
esac

#ACCLIST="laci physics acclegr eoicdesk linac mccops1 lclsops1 lclsops2 lclsops3 lclsops4 lclsops5"  #no edit mode for everybody

if [ -z "${EDM}" ] ; then
    . ~/.bashrc
fi

DEBUG=1

case $ACTION in
  localDisp)
	echo "Starting $fileName.edl"
	 ${CMD} ${MODE} ${fileName} & 
	 ;;
  create)
	echo "Starting $fileName"
	caput CUD:${ROOM}0:MESSAGE "Starting $fileName on $monitor"

	#this is where the display gets set
        DISPLAY=${display}0

        #Kill display if one exists on MONITOR
	cudControl kill $SET $ROOM 
                
        #Update database with user info
	caput $infoPv $cudType 
 	echo caput $infoPv $cudType 
	#Start EDM with FILENAME 
        ${CMD} ${MODE} ${fileName} & 
        echo  ${CMD} ${MODE} ${fileName}
        echo PID is $!
        caput CUD:${ROOM}0:$SET:PID${dispRval} $!
        caput CUD:${ROOM}0:MESSAGE "$cudType started on $monitor"
	;;
  kill)
	echo "Killing display on ${monitor} "
	PROCID=`caget -t CUD:${ROOM}0:$SET:PID${dispRval}`
        echo CUD:${ROOM}0:$SET:PID${dispRval}
        echo "killing ${PROCID}" 
        caput $infoPv NONE
	if [ $fileExtn == "hla" ]; then
	  /usr/local/lcls/tools/script/HLAWrap kill $PROCID
	else
	  kill $PROCID
	fi
	caput CUD:${ROOM}0:MESSAGE "PROCID $PROCID killed on $monitor"
        ;;
  print)
	echo "Printing display on ${monitor}"
#        wName="/usr/local/lcls/tools/edm/display/misc/${fileName}"
        wName=`caget -t ${infoPv}`
        wName="${wName% *}"
	winOpt="-display ${display}"
	winId=`xwininfo  -display ${display} -name "$wName" | grep "$wName" | awk ' {print $4} '`

	if [ -z "${winId}" ]; then
	    echo "X connection refused by ${display} or"
	    echo "No display ${wName} is available" 
            caput CUD:${ROOM}0:MESSAGE "Failed: No display found"
	    exit 1
	fi
	cmdOpt="-window ${winId}"

###	resizeFlag=`caget -t CUD:MCC0:RESIZE.RVAL`
###	if [ resizeFlag > 0 ]; then
###	    winSize=`caget -t CUD:MCC0:RESIZE`
###	    winSize="-resize $winSize"
###            echo winSize="-resize $winSize"
###	fi
###	echo import $winSize $winOpt $cmdOpt ${psFileName}
        import $winOpt $cmdOpt ${psFileName}
	if [ $? -ne 0 ]; then
	    echo "import to ${psFileName} failed"
	    exit 1
	fi        
	echo "import $psFileName DONE"

	#Print
        printerName=`caget -t CUD:${ROOM}0:PRINTER`
echo     lpr -P${printerName} $psFileName
     caput CUD:${ROOM}0:MESSAGE "File /tmp/cudDisplay.ps created"
     kview "/tmp/cudDisplay.ps" &

	if [ $DEBUG -ne 0 ]; then
	    echo xwininfo -stats -display ${display} -name "${wName}" | grep "${wName}" | awk ' {print $4} '
	    echo "resizeFlag is $resizeFlag"
	    echo "winSize is $winSize"
	    echo "import $winSize $winOpt $cmdOpt ${psFileName}"
	    echo "printerName is $printerName"
	    echo "lpr -P${printerName} $psFileName"
	    echo "Printed $infoPv (${psFileName}) to $printerName"
	fi

	;;
  *)
	echo "Sorry don't understand ${ACTION}"
	;;
esac
 

echo DONE!

exit 0
