set -e
RFS=192.168.165.66
#PRC=192.168.165.67
PRC=192.168.1.127
BIT_DIR=../../firmware/prc
BMB7_PATH="../bmb7"

if true; then
#  BIT=../prc-20170517a.bit
#  BIT=./prc-20170726slac.bit
#  BIT=./prc-20170702b.bit
  BIT=$BIT_DIR/prc_sesqui_vivado_20180116.bit
  BIT=$BIT_DIR/prc-sesqui-20180327a.bit
  # any BMB7 r1.0 boards around?
  BIT_OLD=$BIT_DIR/prc_vivado_20180116.bit
  BIT_OLD=$BIT_DIR/prc-20180214a.bit
  python prc.py -a $RFS -b $BIT -r
  python prc.py -a $PRC -b $BIT -r
fi

sh sel_wave_beg.sh $RFS
sh sel_wave_beg.sh $PRC
# SLAC test stand is special?  Or default is strange?
# python $BMB7_PATH/bmb7_gateway.py -a $PRC prc_dsp_cav_sel,1

# Demonstrated problems running icc_lock.sh more than once per FPGA boot
for R in $RFS $PRC; do
  sh icc_lock.sh $R
done

FAIL=0
if python crc_checkn.py $PRC $RFS; then : ; else FAIL=1; fi
if test "$FAIL" = 1; then exit 2; fi
python link_map_check.py $PRC $RFS || exit 2

for R in $RFS; do
  python $BMB7_PATH/bmb7_gateway.py --ip $R -f live_prc_regmap.json --nvs shell_0_dsp_use_fiber_iq,1 shell_1_dsp_use_fiber_iq,1
  python $BMB7_PATH/bmb7_gateway.py --ip $R -f live_prc_regmap.json --nvs trace_keep,0xff
  python station_check.py $R || exit 2
  # Note station_check.py sets dac_{0,1}_sel to OFF for the testing process,
  # but then sets both to PRIMARY_SOURCE if the tests succeed.
  sh sel_gains.sh $R
  # Gain settings in sel_gains.sh are not spectacular,
  # but they are non-zero and almost certainly stable.
done

# sh test1.sh $PRC emulator
# sh test1.sh $RFS emulator

python sel_waves.py -a $RFS -z 0
python sel_waves.py -a $RFS -z 1
echo "Cavity/controller 0"
head ctl0_iq_000
echo "Cavity/controller 1"
head ctl1_iq_000
python get_raw_adcs.py -a $PRC -m 0xff -c 1 -v
# Note that loopback cable shows up as third IQ channel on ctl1_iq_000;
# doesn't match my drawing
# what selection is possible for the channel of cavity field sent over fiber?

# repeat CRC checks
if python crc_checkn.py $PRC $RFS; then : ; else FAIL=1; fi
if test "$FAIL" = 1; then exit 2; fi
echo "$0 complete"
