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

# Defaults
RFS1_IP=192.168.1.30
BIT=
SHA=

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

PYTHON=${PYTHON:-python}
export PYTHONPATH="${PYTHONPATH}:../submodules/FEED/src/python"
rfs_leep_addr="leep://"$RFS1_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 combined PRC/RFS
bash lcls2_rack.sh -r D $bit_opt -w .

# Switch to 20 MHz DAC IF
$PYTHON -m leep.cli $rfs_leep_addr reg if_out_direct=1

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

# Exercise the automated cavity turn-on process
$PYTHON rf_controls.py -j pip2_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
