# Prototype of a "continuous integration" script
set -e

# Defaults
RFS1_IP=192.168.165.84
PRC_IP=192.168.0.103
BIT=
SHA=
SPARE=

while [ $# -gt 0 ];
do
   opt=$1
   case $opt in
      "-h" )
         echo "Usage: lcls2_ci.sh [-h] [-a address] [-b bitfile] [-s spare_ampl]"
         exit 1
         ;;
      "-a" )
         shift
         RFS1_IP=$1
         echo "Connecting to RFS1 IP: $RFS1_IP"
         shift
         ;;
      "-b" )
         shift
         BIT=$1
         SHA=
         shift
         ;;
      "-s" )
         shift
         SPARE=$1
         shift
         ;;
   esac
done

PYTHON=${PYTHON:-python}
export PYTHONPATH="${PYTHONPATH}:../submodules/FEED/src/python"
rfs_leep_addr="leep://"$RFS1_IP
prc_leep_addr="leep://"$PRC_IP

BIT=$(readlink -f $BIT)
echo "Loading bitfile: $BIT"
if test -r "$BIT"; then
   if test -n "$SHA"; then
      echo "$SHA  $BIT" | sha256sum -c
   fi
   bit_opt="-p -b $BIT"
else
   echo "Bitfile $BIT not found"
   bit_opt=""
fi

# Rack checkout with PRC+RFS1
bash lcls2_rack.sh -r C $bit_opt -w .

# Bypass interlocks
PYTHON=$PYTHON bash intlk_byp.sh $RFS1_IP

# Exercise the automated cavity turn-on process
$PYTHON rf_controls.py -j lcls2_emu_leep.json

# Final check that we can go back to zero
# Depends on rf_controls.py cleaning up its tgen mess.
Z=1  # match config of rf_controls.py
if true; then
   echo "Zeroing controller output"
   $PYTHON -m leep.cli $rfs_leep_addr reg \
   shell_${Z}_dsp_fdbk_core_mp_proc_lim_0=0 \
   shell_${Z}_dsp_fdbk_core_mp_proc_lim_1=0 \
   shell_${Z}_dsp_fdbk_core_mp_proc_lim_2=0 \
   shell_${Z}_dsp_fdbk_core_mp_proc_lim_3=0 \
   shell_${Z}_dsp_fdbk_core_mp_proc_sel_en=0
fi

if [ -n "$SPARE" ]; then
   echo "Setting RF1 output 1300 MHz amplitude to $SPARE"
   $PYTHON dac_out.py -a $RFS1_IP -0 -A "$SPARE"
fi

# Enable and test Fiber Ethernet link
echo "Testing Fiber Ethernet on RFS1"
FIB_MAC="12:10:10:10:10:54"
FIB_IP="192.168.0.201"
$PYTHON kintex_program_fiber_interface.py -a $rfs_leep_addr -m $FIB_MAC -i $FIB_IP
ping -c2 $FIB_IP

echo "Testing Fiber Ethernet on PRC"
FIB_MAC="12:10:10:10:10:53"
FIB_IP="192.168.0.203"
$PYTHON kintex_program_fiber_interface.py -a $prc_leep_addr -m $FIB_MAC -i $FIB_IP
ping -c2 $FIB_IP
