#!/bin/bash

########################################################################
#                          Emittance Viewer                            #
# Author: Shawn Alverson                                               #
# Created: 05/05/2009                                                  #
# Modified: 06/28/2010 S.Alverson                                      #
#              - Changed to single time per area ala Colocho CUD       #
#           08/01/2011 S.Alverson                                      #
#              - Changed print format HTML for E-Log print             #
#              - Trimmed out unnecessary/unused code                   #
#           08/04/2011 S.Alverson                                      #
#              - Added Beam Parameter info to print title              #
#           12/19/2013 S.Alverson                                      #
#              - Added WS02 emittance info                             #
#                                                                      #
# Inspired by showemit.m by H. Smith                                   #
#                                                                      #
# showemit displays current emittance and bmag measurement values for  #
# all areas of the accelerator and displays them in the terminal       #
# window along with a calculated time for how old the data is in hours #
#                                                                      #
# Inputs:                                                              #
#       -p      Prints color-coded text of emittances to the mcc-elog  #
#       -l      Prompts user for new set of limits for color rules     #
#       -h      Shows help information                                 #
#       NONE    Displays emittances in terminal window only            #
#                                                                      #
# Line Color Coding:                                                   #
#       EMITs/BMAGs                                                    #
#            Green: Data is less than .HIGH PV limit                   #
#            Red  : Data is greater than .HIGH PV limit                #
#       Age Timestamps                                                 #
#            Green: Data less than 4 hours old                         #
#            Yellow: Data between 4 and 8 hours old                    #
#            Red: Data more than 8 hours old                           #
#                                                                      #
########################################################################

# Check if server is facet or lcls
if [ $(uname -n | grep facet) ];then
    fshowemit "$@"
    exit 0
fi

# Define color options
white="\033[1;37m\033[40m"
gray="\033[0;37m\033[40m"
red="\033[0;31m\033[40m"
yellow="\033[1;33m\033[40m"
green="\033[0;32m\033[40m"

#TITLE="Emittance Measurements"
PRTLOG=""
TSET=""
Warn=4
Alarm=8

# Check Options
if [ $# -ne 0 ];then
   while getopts "ltph" Option
   do
      case $Option in
         l  )  echo -n "Warning limit: "
               read Warn
               echo -n "Alarm limit: "
               read Alarm;;
         p  )  PRTLOG="yes";;
         *  )  echo -e "\nSyntax: showemit [OPTION] [TITLE]"
               echo -e "Options: -p  Print to mccelog"
               echo -e "         -l  Edit Color limits"
               echo -e "         -h  Help\n"
               echo -e "If no title given default title is used.\n"
               exit;;
      esac
   done
   shift $(($OPTIND-1))
fi

# Get OTR2 emits and bmags
OTR2=($(caget -f 3 OTRS:IN20:571:EMITN_X OTRS:IN20:571:EMITN_Y OTRS:IN20:571:BMAG_X OTRS:IN20:571:BMAG_Y))
OTMULTX=$(echo "scale=3; ${OTR2[1]}*${OTR2[5]}" | bc -l | awk '{printf "%4.4g", $1}')
OTMULTY=$(echo "scale=3; ${OTR2[3]}*${OTR2[7]}" | bc -l | awk '{printf "%4.4g", $1}')
OTTIME=$(caget -t OTRS:IN20:571:EMIT_TIME)

# Get WS02 emits and bmags
WS02=($(caget -f 3 WIRE:IN20:561:EMITN_X WIRE:IN20:561:EMITN_Y WIRE:IN20:561:BMAG_X WIRE:IN20:561:BMAG_Y))
WS02MULTX=$(echo "scale=3; ${WS02[1]}*${WS02[5]}" | bc -l | awk '{printf "%4.4g", $1}')
WS02MULTY=$(echo "scale=3; ${WS02[3]}*${WS02[7]}" | bc -l | awk '{printf "%4.4g", $1}')
WS02TIME=$(caget -t WIRE:IN20:561:EMIT_TIME)

# Get WS12 emits and bmags
WS12=($(caget -f 3 WIRE:LI21:293:EMITN_X WIRE:LI21:293:EMITN_Y WIRE:LI21:293:BMAG_X WIRE:LI21:293:BMAG_Y))
WSMULTX=$(echo "scale=3; ${WS12[1]}*${WS12[5]}" | bc -l | awk '{printf "%4.4g", $1}')
WSMULTY=$(echo "scale=3; ${WS12[3]}*${WS12[7]}" | bc -l | awk '{printf "%4.4g", $1}')
WSTIME=$(caget -t WIRE:LI21:293:EMIT_TIME)

# Get LI28 emits and bmags
LI28=($(caget -f 3 WIRE:LI28:144:EMITN_X WIRE:LI28:144:EMITN_Y WIRE:LI28:144:BMAG_X WIRE:LI28:144:BMAG_Y))
LIMULTX=$(echo "scale=3; ${LI28[1]}*${LI28[5]}" | bc -l | awk '{printf "%4.4g", $1}')
LIMULTY=$(echo "scale=3; ${LI28[3]}*${LI28[7]}" | bc -l | awk '{printf "%4.4g", $1}')
LITIME=$(caget -t WIRE:LI28:144:EMIT_TIME)

# Get LTUH emits and bmags
LTUH=($(caget -f 3 WIRE:LTUH:735:EMITN_X WIRE:LTUH:735:EMITN_Y WIRE:LTUH:735:BMAG_X WIRE:LTUH:735:BMAG_Y))
LTMULTX=$(echo "scale=3; ${LTUH[1]}*${LTUH[5]}" | bc -l | awk '{printf "%4.4g", $1}')
LTMULTY=$(echo "scale=3; ${LTUH[3]}*${LTUH[7]}" | bc -l | awk '{printf "%4.4g", $1}')
LTTIME=$(caget -t WIRE:LTUH:735:EMIT_TIME)

# Get LTUS emits and bmags
LTUS=($(caget -f 3 WIRE:LTUS:735:EMITN_X WIRE:LTUS:735:EMITN_Y WIRE:LTUS:735:BMAG_X WIRE:LTUS:735:BMAG_Y))
LTSMULTX=$(echo "scale=3; ${LTUS[1]}*${LTUS[5]}" | bc -l | awk '{printf "%4.4g", $1}')
LTSMULTY=$(echo "scale=3; ${LTUS[3]}*${LTUS[7]}" | bc -l | awk '{printf "%4.4g", $1}')
LTSTIME=$(caget -t WIRE:LTUS:735:EMIT_TIME)


# Get Limits for emits and bmags and sort color rules
count=1
for i in "${OTR2[*]}" "${WS02[*]}" "${WS12[*]}" "${LI28[*]}" "${LTUH[*]}" "${LTUS[*]}"
do 
   for index in $(seq 1 2 7)
   do
      input=$(echo "\$$index")
      PV=$(echo $i | awk '{print '$input'}')
      HIGH=($(caget -t $PV.HIGH)) # $PV.HIHI))
      #echo "Getting PV: $PV.HIGH returning: $HIGH"

      ind=$(echo "\$$(($index+1))")
      VAL=$(echo $i | awk '{print '$ind'}')
      if [ $(echo "$VAL <= $HIGH" | bc) -eq 1 ];then
         #echo "$VAL <= $HIGH shows GREEN"
         Color[$count]=$green
      else
         Color[$count]=$red
         #echo "$VAL > $HIGH shows RED"
      fi
      let "count += 1"
   done
done

# Add leading and trailing zeroes to values that need them
count=1
for i in $OTMULTX $OTMULTY $WS02MULTX $WS02MULTY $WSMULTX $WSMULTY $LIMULTX $LIMULTY $LTMULTX $LTMULTY $LTSMULTX $LTSMULTY
do
   case $i in
      .*                ) Mult[$count]=$(echo 0$i);;
      [0-9].[0-9]       ) Mult[$count]=$(echo "$i"00);;
      [0-9].[0-9][0-9]  ) Mult[$count]=$(echo "$i"0);;
      *                 ) Mult[$count]=$i;;
   esac
   let "count += 1"
done

# Format time string and take difference
count=17
index=1
for i in "${OTTIME[0]} ${OTTIME[1]}" "${WS02TIME[0]} ${WS02TIME[1]}" "${WSTIME[0]} ${WSTIME[1]}" "${LITIME[0]} ${LITIME[1]}" "${LTTIME[0]} ${LTTIME[1]}" "${LTSTIME[0]} ${LTSTIME[1]}"
do
   diff=$(($(date "+%s")-$(date -d "$i" "+%s")))
   Time[$index]=$(echo "scale=3; $diff/3600" | bc -l)
   case ${Time[$index]} in
      .*                      ) Time[$index]=$(echo 0${Time[$index]});;                                # Add starting zero if needed
      [0-9][0-9][0-9][0-9].*  ) Time[$index]=$(echo ${Time[$index]} | awk '{printf "%4.4g", $1}')      # Trim trailing "."
                                Time[$index]=$(echo " ${Time[$index]}");;                              # Add leading space for alignment
      *                       ) Time[$index]=$(echo ${Time[$index]} | awk '{printf "%#4.4g", $1}') ;;  # Format data for length of 4 or max dec. of 4
   esac

   # Set line color rules
   if [ $(echo "${Time[$index]} <= $Warn" | bc) -eq 1 ];then
      Color[$count]=$green
   elif [ $(echo "${Time[$index]} > $Warn" | bc) -eq 1 ];then
      Color[$count]=$red
   else
      Color[$count]=$white
   fi
   let "count += 1"
   let "index += 1"
done

# Format data and display in command window
echo -e "$EINS $white                                                                             \033[0m"
echo -e "$EINS $white      | EMITX | BMAGX | EMITX*BMAGX | EMITY | BMAGY | EMITY*BMAGY | AGE(hrs) \033[0m"
echo -e "$EINS $white-----------------------------------------------------------------------------\033[0m"
echo -e "$EINS $white OTR2 | ${Color[1]}"${OTR2[1]}"$white | ${Color[3]}"${OTR2[5]}"$white |    $gray"${Mult[1]}"$white    |   -   |   -   |      -      |  ${Color[17]}"${Time[1]}"   \033[0m"
echo -e "$EINS $white WS02 | ${Color[5]}"${WS02[1]}"$white | ${Color[7]}"${WS02[5]}"$white |    $gray"${Mult[3]}"$white    |   -   |   -   |      -      |  ${Color[18]}"${Time[2]}"   \033[0m"
echo -e "$EINS $white WS12 | ${Color[9]}"${WS12[1]}"$white | ${Color[11]}"${WS12[5]}"$white |    $gray"${Mult[5]}"$white    |   -   |   -   |      -      |  ${Color[19]}"${Time[3]}"   \033[0m"
echo -e "$EINS $white LI28 | ${Color[13]}"${LI28[1]}"$white | ${Color[15]}"${LI28[5]}"$white |    $gray"${Mult[7]}"$white    |   -   |   -   |      -      |  ${Color[20]}"${Time[4]}"   \033[0m"
echo -e "$EINS $white LTUH | ${Color[17]}"${LTUH[1]}"$white | ${Color[19]}"${LTUH[5]}"$white |    $gray"${Mult[9]}"$white    |   -   |   -   |      -      |  ${Color[21]}"${Time[5]}"   \033[0m"
echo -e "$EINS $white OTR2 |   -   |   -   |      -      | ${Color[2]}"${OTR2[3]}"$white | ${Color[4]}"${OTR2[7]}"$white |    $gray"${Mult[2]}"$white    |  ${Color[17]}"${Time[1]}"   \033[0m"
echo -e "$EINS $white WS02 |   -   |   -   |      -      | ${Color[6]}"${WS02[3]}"$white | ${Color[8]}"${WS02[7]}"$white |    $gray"${Mult[4]}"$white    |  ${Color[18]}"${Time[2]}"   \033[0m"
echo -e "$EINS $white WS12 |   -   |   -   |      -      | ${Color[10]}"${WS12[3]}"$white | ${Color[12]}"${WS12[7]}"$white |    $gray"${Mult[6]}"$white    |  ${Color[19]}"${Time[3]}"   \033[0m"
echo -e "$EINS $white LI28 |   -   |   -   |      -      | ${Color[14]}"${LI28[3]}"$white | ${Color[16]}"${LI28[7]}"$white |    $gray"${Mult[8]}"$white    |  ${Color[20]}"${Time[4]}"   \033[0m"
echo -e "$EINS $white LTUH |   -   |   -   |      -      | ${Color[18]}"${LTUH[3]}"$white | ${Color[20]}"${LTUH[7]}"$white |    $gray"${Mult[10]}"$white    |  ${Color[21]}"${Time[5]}"   \033[0m"
echo -e "$EINS $white                                                                             \033[0m"

# Reset all format changes
tput sgr0

# If print to e-log, create .xml file and format color rules
if [ "$PRTLOG" != "" ];then
   # Redefine colors for css
   for i in $(seq 1 1 24)
   do
      case ${Color[$i]} in
         "$red"     ) Color[$i]="emitBad";;
         "$green"   ) Color[$i]="emitGood";;
         *          ) Color[$i]="emitInvalid";;
      esac 
   done
   Color[0]="emitMulti"

   # Get relevant beam information
   energy=$(caget -t SIOC:SYS0:ML00:AO500)
   penergy=$(caget -f 0 -t SIOC:SYS0:ML00:AO627)
   charge=$(caget -t FBCK:BCI0:1:CHRGSP)
   Ipk=$(caget -f 0 -t SIOC:SYS0:ML00:AO195) 
   blen=$(caget -f 0 -t SIOC:SYS0:ML00:AO820)

   TITLE=$(echo "LCLS Emittance Measurements - $penergy eV ($energy GeV), $charge nC, $blen fs ($Ipk A)")

   # Create .xml file (&nbsp)
   fname=$(echo '/tmp/'$(date "+%Y%m%d_%H%M%S_%N")'.xml')
   echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" > $fname
   echo "<log_entry type=\"LOGENTRY\">" >> $fname
   echo "<title><![CDATA[$TITLE]]></title>" >> $fname
   echo "<program>152</program>" >> $fname
   echo '<timestamp>'$(date "+%Y/%m/%d %T")'</timestamp>' >> $fname
   echo "<priority>NORMAL</priority>" >> $fname
   echo "<os_user>nobody</os_user>" >> $fname
   echo "<hostname>mccelog</hostname>" >> $fname
   echo "<text type =\"text/plain\"><![CDATA[<table class="emittanceTable">" >> $fname
   echo "<tr><th></th><th>EMITX</th><th>BMAGX</th><th>EMITX*BMAGX</th><th>EMITY</th><th>BMAGY</th><th>EMITY*BMAGY</th><th>AGE(hrs)</th></tr>" >> $fname
   echo "<tr><th>OTR2</th>" >> $fname
   echo "<td class=${Color[1]}>${OTR2[1]}</td><td class=${Color[3]}>${OTR2[5]}</td><td class=${Color[0]}>${Mult[1]}</td>" >> $fname
   echo "<td class=${Color[2]}>${OTR2[3]}</td><td class=${Color[4]}>${OTR2[7]}</td><td class=${Color[0]}>${Mult[2]}</td><td class=$Color[17]>${Time[1]}</td></tr>" >> $fname
   echo "<tr><th>WS02</th>" >> $fname
   echo "<td class=${Color[5]}>${WS02[1]}</td><td class=${Color[7]}>${WS02[5]}</td><td class=${Color[0]}>${Mult[3]}</td>" >> $fname
   echo "<td class=${Color[6]}>${WS02[3]}</td><td class=${Color[8]}>${WS02[7]}</td><td class=${Color[0]}>${Mult[4]}</td><td class=$Color[18]>${Time[2]}</td></tr>" >> $fname
   echo "<tr><th>WS12</th>" >> $fname
   echo "<td class=${Color[9]}>${WS12[1]}</td><td class=${Color[11]}>${WS12[5]}</td><td class=${Color[0]}>${Mult[5]}</td>" >> $fname
   echo "<td class=${Color[10]}>${WS12[3]}</td><td class=${Color[12]}>${WS12[7]}</td><td class=${Color[0]}>${Mult[6]}</td><td class=$Color[19]>${Time[3]}</td></tr>" >> $fname
   echo "<tr><th>LI28</th>" >> $fname
   echo "<td class=${Color[13]}>${LI28[1]}</td><td class=${Color[15]}>${LI28[5]}</td><td class=${Color[0]}>${Mult[7]}</td>" >> $fname
   echo "<td class=${Color[14]}>${LI28[3]}</td><td class=${Color[16]}>${LI28[7]}</td><td class=${Color[0]}>${Mult[8]}</td><td class=$Color[20]>${Time[4]}</td></tr>" >> $fname
   echo "<tr><th>LTUH</th>" >> $fname
   echo "<td class=${Color[17]}>${LTUH[1]}</td><td class=${Color[19]}>${LTUH[5]}</td><td class=${Color[0]}>${Mult[9]}</td>" >> $fname
   echo "<td class=${Color[18]}>${LTUH[3]}</td><td class=${Color[20]}>${LTUH[7]}</td><td class=${Color[0]}>${Mult[10]}</td><td class=$Color[21]>${Time[5]}</td></tr>" >> $fname
   echo "</table>]]></text>" >> $fname
   echo "<logbook>mcc</logbook>" >> $fname  
   echo "<segment>LCLS</segment>" >> $fname
   echo "<log_user>mcc_auto</log_user>" >> $fname
   echo "</log_entry>" >> $fname
   
   xml2elog $fname
   echo "Print Completed!"
fi

exit 0
