#!/bin/bash
#==============================================================
# luViewTimingData
#
# Facility:  SLAC/LCLS
#
# Run script to compare timing data between VMS and EPICS, after
# copying VMS timing config and running Dayle's script to extract
# the values for 'caput's.
#
# Usage: luCompareTimingData <location>
#
# Arguments: 
#            location: ioc location name, for example li28
#            config: config file name
#               for LI21-LI30 it is tim21-30.cnf
#               for LI20 it is tim02-24.cnf
# 
#----------------------------------------------------------------------------
# Mod:
#        
#==============================================================

loca=`echo $1 | tr '[:upper:]' '[:lower:]'`

LOCA=`echo $1 | tr '[:lower:]' '[:upper:]'`

config=`echo $2 | tr '[:upper:]' '[:lower:]'`

echo  Diffing ${LOCA} Timing SLC and EPICS Settings - takes a couple minutes...

scriptpath='/home/iocegr/dayle'
workpath='/home/physics/linacUpgrade/trig-diff'
datapath=/u1/lcls/epics/ioc/data/ioc-${loca}-cv01/slcdata

current=`pwd`

cd ${workpath}

# If local timing config is > 1 hour old, copy a new one over from VMS
if [ "$(( $(date +"%s") - $(stat -c "%Y" ../${config}) ))" -gt "3600" ]; then    

    echo Timing config file is older than 1 hour. Copying new file over.
    get_latest_file    
    sleep 20 # Add wait to copy files from VMS
else
    echo Timing config file is less than 1 hour old. Using this file.
fi

# Run Dayle's script to convert SCP config to PV put script
scpPull ${config} ${scriptpath}/trigName.LUT ${LOCA} > trig-${loca} 2> err

# If this is LI20, remove  PVs not in crates 3 and 4 (we are not using the other crates)

if [ "${LOCA}" == "LI20" ]; then
    grep -v "PDU:LI20:5" trig-${loca} | grep -v "TRIG:LI20:5" | grep -v "PDU:LI20:2" | grep -v "TRIG:LI20:2" | grep -v "SBST:LI20:1" \
      | grep -v "KLYS:LI20:11" | grep -v "KLYS:LI20:21" | grep -v "KLYS:LI20:31" | grep -v "KLYS:LI20:41"> trig-${loca}.temp
    cp trig-${loca}.temp trig-${loca}
fi

# Remove all but PV names and values.
# For TDES, klugey trick: multiply then divide by ten in order to get slc and EPICS numbers in same format
grep -v "\#" trig-${loca} | grep caput | grep ":" | grep -v Creating | grep -v TMVA | awk '{print $2 " " $3 " " $4 " " $5}' > trig-${loca}.temp
perl -p -e 's/"//g' trig-${loca}.temp | awk '/TDES/ {print $1 " " $2*10/10 } !/TDES/ {print $0}' > trig-${loca}.slcdata

# Extract PV names
awk '{print $1}' trig-${loca}.slcdata > trig-${loca}.epicspvlist

# Display SLC data and proposed EPICS PV settings to user to review
#awk '{print $2 $3}' trig-${loca} | grep ${LOCA} > tim_${loca}_slcdata

# Build caget script. For TDES, klugey trick: multiply then divide by ten in order to get slc
# and EPICS numbers in same format
awk '{print "caget -g 8 " $1}' trig-${loca}.epicspvlist > trig-${loca}.epicsscript
chmod +x trig-${loca}.epicsscript
./trig-${loca}.epicsscript | awk '{print $1 " " $2 " " $3 " " $4}' | awk '/TDES/ {print $1 " " $2*10/10 } !/TDES/ {print $0}' > trig-${loca}.epicsdata

# Extract values only and output them to a file
awk '{$1=",";print}' trig-${loca}.epicsdata > trig-${loca}.epicsvals
awk '{$1=",";print}' trig-${loca}.slcdata > trig-${loca}.slcvals

#trig-${loca}.pvlist | awk '{print $1 " " $2 " " $3 " " $4}' > trig-${loca}.epicsdata

## Get EPICS PV values
#caGet1 trig-${loca}.pvlist | awk '{print $1 " " $2 " " $3 " " $4}' > trig-${loca}.epicsdata

# Clean up data for easier diffing
perl -pi -e 's/Reactivate/1/' trig-${loca}.epicsvals trig-${loca}.slcvals
perl -pi -e 's/Deactivate/0/' trig-${loca}.epicsvals trig-${loca}.slcvals
perl -pi -e 's/BC1 Default/Default BC1/' trig-${loca}.epicsvals trig-${loca}.slcvals
perl -pi -e 's/BC1 BCSFAULT/BCSFAULT BC1/' trig-${loca}.epicsvals trig-${loca}.slcvals
perl -pi -e 's/\"//g' trig-${loca}.epicsvals trig-${loca}.slcvals

countslc=`wc -l trig-${loca}.slcvals | awk '{print $1}'`
countepics=`wc -l trig-${loca}.epicsvals | awk '{print $1}'`
countpvs=`wc -l trig-${loca}.epicspvlist | awk '{print $1}'`

if [ ${countslc} = ${countepics} -a ${countslc} = ${countpvs} ]; then
    echo 'SLC and EPICS caget results length match. Proceed.'
else
    echo 'SLC and EPICS caget results have different lengths; cannot diff these files'
    exit 0
fi

# Paste PV names, SLC values, and EPICS values into single file and remove whitespace
paste trig-${loca}.epicspvlist trig-${loca}.slcvals trig-${loca}.epicsvals | awk '{$1=$1};1' > trig-${loca}.data

# Extract lines where SLC and EPICS values do not match; add formatting to make it readable
awk 'BEGIN {FS="," ; 
printf "PV name                        | SLC value                 | EPICS value \n---------------------------------------------------------------------------------\n"} ; 
($2!~$3) {printf "%-30s | %-25s | %s\n",$1,$2,$3 }' trig-${loca}.data > trig-${loca}.diff

datestr=`date '+%d-%h-%Y-%h:%M.%S'`

cp trig-${loca}.diff ${datapath}/trig-${loca}.diff.${datestr}

# Filter out readbacks for more useful diff (and SID for now--SLC provides in signed format; EPICS in unsigned)
grep -v TMSK trig-${loca}.diff > trig-${loca}.diff.filtered

cp trig-${loca}.diff.filtered ${datapath}/trig-${loca}.diff.filtered.${datestr}

# Display difference for users to view
cat trig-${loca}.diff.filtered
echo Copying file to ${datapath}...

cd ${current}

echo Done. Exiting

exit 0
