#!/bin/bash

########################################################################
#                          Emittance Viewer                            #
# Author: Shawn Alverson                                               #
# Created: 04/20/2012                                                  #
# Modified:                                                            #
#                                                                      #
# Based on showemit script for LCLS                                    #
#                                                                      #
# 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  #
#       -t      Prompts user for the title for the log entry           #
#       -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                           #
#                                                                      #
########################################################################

# 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"

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 formatted LI02 emits and bmag
LI02=($(caget SIOC:SYS1:ML00:AO209 SIOC:SYS1:ML00:AO213 SIOC:SYS1:ML00:AO212 SIOC:SYS1:ML00:AO216))
for index in $(seq 1 2 7)
do
   LI02[$index]=$(printf "%0.5s" ${LI02[$index]})
done      
LI02EMITX=$(echo "scale=3; ${LI02[1]}/${LI02[5]}" | bc -l) #4.4g
LI02EMITY=$(echo "scale=3; ${LI02[3]}/${LI02[7]}" | bc -l)
LI02TIME=$(caget -t SIOC:SYS1:ML00:AO209TS)

# Get formatted LI04 emits and bmags
LI04=($(caget SIOC:SYS1:ML00:AO217 SIOC:SYS1:ML00:AO221 SIOC:SYS1:ML00:AO220 SIOC:SYS1:ML00:AO224))
for index in $(seq 1 2 7)
do
   LI04[$index]=$(printf "%0.5s" ${LI04[$index]})
done 
LI04EMITX=$(echo "scale=3; ${LI04[1]}/${LI04[5]}" | bc -l)
LI04EMITY=$(echo "scale=3; ${LI04[3]}/${LI04[7]}" | bc -l)
LI04TIME=$(caget -t SIOC:SYS1:ML00:AO217TS)

# Get formatted LI11 emits and bmags
LI11=($(caget SIOC:SYS1:ML00:AO225 SIOC:SYS1:ML00:AO229 SIOC:SYS1:ML00:AO228 SIOC:SYS1:ML00:AO232))
for index in $(seq 1 2 7)
do
   LI11[$index]=$(printf "%0.5s" ${LI11[$index]})
done 
LI11EMITX=$(echo "scale=3; ${LI11[1]}/${LI11[5]}" | bc -l)
LI11EMITY=$(echo "scale=3; ${LI11[3]}/${LI11[7]}" | bc -l)
LI11TIME=$(caget -t SIOC:SYS1:ML00:AO225TS)

# Get formatted LI18 emits and bmags
LI18=($(caget SIOC:SYS1:ML00:AO233 SIOC:SYS1:ML00:AO237 SIOC:SYS1:ML00:AO236 SIOC:SYS1:ML00:AO240))
for index in $(seq 1 2 7)
do
   LI18[$index]=$(printf "%0.5s" ${LI18[$index]})
done 
LI18EMITX=$(echo "scale=3; ${LI18[1]}/${LI18[5]}" | bc -l)
LI18EMITY=$(echo "scale=3; ${LI18[3]}/${LI18[7]}" | bc -l)
LI18TIME=$(caget -t SIOC:SYS1:ML00:AO233TS)

# Get LI20 Wire Sizes
LI20=($(caget WIRE:LI20:3179:XRMS WIRE:LI20:3179:YRMS))
for index in $(seq 1 2 3)
do
   LI20[$index]=$(printf "%0.5s" ${LI20[$index]})
done


# Get Limits for emits and bmags and sort color rules
count=1
for i in "${LI02[*]}" "${LI04[*]}" "${LI11[*]}" "${LI18[*]}"
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 $LI02EMITX $LI02EMITY $LI04EMITX $LI04EMITY $LI11EMITX $LI11EMITY $LI18EMITX $LI18EMITY
do
   if [ $(echo $i | wc -L) -le 4 ];then  #Add leading zeros
       i=0$i;
   fi
   Emit[$count]=$(echo $i | awk '{printf "%0.5s", $1}') #tmp, %2.4g

   let "count += 1"
done

# Format time string and take difference
count=17
index=1
for i in "${LI02TIME[0]} ${LI02TIME[1]}" "${LI04TIME[0]} ${LI04TIME[1]}" "${LI11TIME[0]} ${LI11TIME[1]}" "${LI18TIME[0]} ${LI18TIME[1]}"
do
   diff=$(($(date "+%s")-$(date -d "$i" "+%s")))
   Time[$index]=$(echo "scale=3; $diff/3600" | bc -l | awk '{printf "%0.5s", $1}')

   # Add leading zeros if necessary
   if [ $(echo "${Time[$index]}" | wc -L) -le 4 ];then  #Add leading zeros
       Time[$index]=0${Time[$index]};
   fi

   # 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 LI02 | $gray"${Emit[1]}"$white | ${Color[3]}"${LI02[5]}"$white |    ${Color[1]}"${LI02[1]}"$white    |   -   |   -   |      -      |  ${Color[17]}"${Time[1]}"   \033[0m"
echo -e "$EINS $white LI04 | $gray"${Emit[3]}"$white | ${Color[7]}"${LI04[5]}"$white |    ${Color[5]}"${LI04[1]}"$white    |   -   |   -   |      -      |  ${Color[18]}"${Time[2]}"   \033[0m"
echo -e "$EINS $white LI11 | $gray"${Emit[5]}"$white | ${Color[11]}"${LI11[5]}"$white |    ${Color[9]}"${LI11[1]}"$white    |   -   |   -   |      -      |  ${Color[19]}"${Time[3]}"   \033[0m"
echo -e "$EINS $white LI18 | $gray"${Emit[7]}"$white | ${Color[15]}"${LI18[5]}"$white |    ${Color[13]}"${LI18[1]}"$white    |   -   |   -   |      -      |  ${Color[20]}"${Time[4]}"   \033[0m"
echo -e "$EINS $white LI02 |   -   |   -   |      -      | $gray"${Emit[2]}"$white | ${Color[4]}"${LI02[7]}"$white |    ${Color[2]}"${LI02[3]}"$white    |  ${Color[17]}"${Time[1]}"   \033[0m"
echo -e "$EINS $white LI04 |   -   |   -   |      -      | $gray"${Emit[4]}"$white | ${Color[8]}"${LI04[7]}"$white |    ${Color[6]}"${LI04[3]}"$white    |  ${Color[18]}"${Time[2]}"   \033[0m"
echo -e "$EINS $white LI11 |   -   |   -   |      -      | $gray"${Emit[6]}"$white | ${Color[12]}"${LI11[7]}"$white |    ${Color[10]}"${LI11[3]}"$white    |  ${Color[19]}"${Time[3]}"   \033[0m"
echo -e "$EINS $white LI18 |   -   |   -   |      -      | $gray"${Emit[8]}"$white | ${Color[16]}"${LI18[7]}"$white |    ${Color[14]}"${LI18[3]}"$white    |  ${Color[20]}"${Time[4]}"   \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:SYS1:ML00:AO069)
   charge=$(caget -e 2 -t LI10:TORO:133:DATA)
   blen=$(caget -f 0 -t BLEN:LI20:3014:BRAW)

   TITLE=$(echo "FACET Emittance Measurements - $energy GeV, $charge Nel, $blen arb (YARMAX)")

   # 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>LI02</th>" >> $fname
   echo "<td class=${Color[0]}>${Emit[1]}</td><td class=${Color[3]}>${LI02[5]}</td><td class=${Color[1]}>${LI02[1]}</td>" >> $fname
   echo "<td class=${Color[0]}>${Emit[2]}</td><td class=${Color[4]}>${LI02[7]}</td><td class=${Color[2]}>${LI02[3]}</td><td class=$Color[17]>${Time[1]}</td></tr>" >> $fname
   echo "<tr><th>LI04</th>" >> $fname
   echo "<td class=${Color[0]}>${Emit[3]}</td><td class=${Color[7]}>${LI04[5]}</td><td class=${Color[5]}>${LI04[1]}</td>" >> $fname
   echo "<td class=${Color[0]}>${Emit[4]}</td><td class=${Color[8]}>${LI04[7]}</td><td class=${Color[6]}>${LI04[3]}</td><td class=$Color[18]>${Time[2]}</td></tr>" >> $fname
   echo "<tr><th>LI11</th>" >> $fname
   echo "<td class=${Color[0]}>${Emit[5]}</td><td class=${Color[11]}>${LI11[5]}</td><td class=${Color[9]}>${LI11[1]}</td>" >> $fname
   echo "<td class=${Color[0]}>${Emit[6]}</td><td class=${Color[12]}>${LI11[7]}</td><td class=${Color[10]}>${LI11[3]}</td><td class=$Color[19]>${Time[3]}</td></tr>" >> $fname
   echo "<tr><th>LI18</th>" >> $fname
   echo "<td class=${Color[0]}>${Emit[7]}</td><td class=${Color[15]}>${LI18[5]}</td><td class=${Color[13]}>${LI18[1]}</td>" >> $fname
   echo "<td class=${Color[0]}>${Emit[8]}</td><td class=${Color[16]}>${LI18[7]}</td><td class=${Color[14]}>${LI18[3]}</td><td class=$Color[20]>${Time[4]}</td></tr>" >> $fname
   echo "</table>]]></text>" >> $fname
   echo "<logbook>mcc</logbook>" >> $fname  
   echo "<segment>FACET</segment>" >> $fname
   echo "<log_user>mcc_auto</log_user>" >> $fname
   echo "</log_entry>" >> $fname
   
   xml2elog $fname
   echo "Print Completed!"
fi

exit 0
