#!/bin/bash
#==============================================================
# luViewTimingData
#
# Facility:  SLAC/LCLS
#
# Run script to copy timing config from VMS, run Dayle's script to 
# create a PV caput script, display saved SLC timing data, and then 
# optionally put the values to EPICS
#
# Usage: luViewTimingData <location>
#
# Arguments: 
#            location: ioc location name, for example li28
#            config: config file name
# 
#----------------------------------------------------------------------------
# Mod:
#        
#==============================================================

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

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

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

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

current=`pwd`

cd ${workpath}

# Copy over timing config
echo Copying timing config
get_latest_file
echo Wait 30 seconds to copy file
sleep 30 # Add wait to copy files from VMS

echo Running scpPull

# Run Dayle's script to convert SCP config to PV put script
# Remove out TDEFs; these are hard-coded in EPICS database
# - Temporary - remove TMVAs; PVs are not online and it slows down script
scpPull ${config} ${scriptpath}/trigName.LUT ${LOCA} | grep -v TDEF | grep -v TMVA > trig-${loca}.out 2> err
# Temporary fix
#perl -pi -e 's/\# NO DEFAULT RULE so no //' trig-${loca}.out 

echo Processing files

chmod +x trig-${loca}.out

# Extract PV names
awk '{print $2}' trig-${loca}.out | grep ${LOCA} > tim_${loca}_pvlist

# Get list of TMSK PVs to process and create PV put script
grep TMSK tim_${loca}_pvlist > tim_${loca}_pvlist_tmsk

./prepend_caput tim_${loca}_pvlist_tmsk temp

./append_proc temp tim_${loca}_pvlist_tmsk.out

perl -pi -e 's/TMSK[0-2]/TMSK_FANOUT/' tim_${loca}_pvlist_tmsk.out 
grep caput tim_${loca}_pvlist_tmsk.out | sort -u > temp2
mv temp2 tim_${loca}_pvlist_tmsk.out

chmod +x tim_${loca}_pvlist_tmsk.out

rm -f temp

echo Display settings

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

caGet1 tim_${loca}_pvlist > tim_${loca}_epicsdata

#xterm -hold -geometry 100x50+620+20 -T "Diff ${LOCA} SLC Timing Settings and current EPICS PV values" -e diff tim_${loca}_slcdata tim_${loca}_epicsdata&

xterm -hold -geometry 100x50+920+220 -T "${LOCA} Timing Settings" -e cat trig-${loca}.out&

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

# Copy file to data area
cp trig-${loca}.out ${datapath}/trig-${loca}.out.${datestr}

echo 'Putting timing data...'
./trig-${loca}.out
./tim_${loca}_pvlist_tmsk.out
echo 'Done copying timing data'

cd ${current}

exit 0
