set -e
SYS=${1:-sys1}
RFS1=${SYS}_rfs1
RFS2=${SYS}_rfs2
PRC=${SYS}_prc
ALL="$RFS1 $RFS2 $PRC"
if true; then
  BIT=~ldoolitt/lcls2_bits/prc-20180306a.bit
  python prc.py -a $RFS1 -b $BIT -r
  python prc.py -a $RFS2 -b $BIT -r
  python prc.py -a $PRC  -b $BIT -r
fi
for R in $ALL; do
  sh sel_wave_beg.sh $R
  sh icc_lock.sh $R
done

BMB7_PATH="../bmb7"
GATEWAY="python $BMB7_PATH/bmb7_gateway.py -f live_prc_regmap.json"

for R in $ALL; do
  python $BMB7_PATH/qsfp_i2c_setup.py -r -i -a $R
done

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

check_fiber_iq () {
  for R in $RFS1 $RFS2; do
    $GATEWAY --ip $R --nvs shell_0_dsp_use_fiber_iq shell_1_dsp_use_fiber_iq | awk -v r=$R '/^\[/{print r, "use_fiber_iq", $0}'
  done
}

for R in $RFS1 $RFS2; do
  echo "$R: enabling DSP fiber input and checking station"
  $GATEWAY --ip $R --nvs shell_0_dsp_use_fiber_iq,1 shell_1_dsp_use_fiber_iq,1
  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

for R in $ALL; do
  python $BMB7_PATH/r1/read_board_monitors.py -t $R -n 1
done

for R in $RFS1 $RFS2; do
  python sel_waves.py -a $R -z 0
  python sel_waves.py -a $R -z 1
  echo "$R Cavity/controller 0"
  head ctl0_iq_000
  echo "$R Cavity/controller 1"
  head ctl1_iq_000
done
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?

# define the chassis locations to chitchat module
# subset of cc_setup.sh
# for test purposes, turns on both
#  cav_interlock_permit = cavity_status[31]
#  cav_detune_valid     = cavity_status[30]
$GATEWAY --ip $RFS1 --nvs cc_loc1,1 cct1_cavity0_status_aux,0x3040 cct1_cavity1_status_aux,0x3050
$GATEWAY --ip $RFS2 --nvs cc_loc1,2 cct1_cavity0_status_aux,0x3060 cct1_cavity1_status_aux,0x3070
sh cc_reset.sh $RFS1
sh cc_reset.sh $RFS2

if python crc_checkn.py $PRC $RFS1 $RFS2; then : ; else FAIL=1; fi
if test "$FAIL" = 1; then exit 2; fi
check_fiber_iq
echo "cmts_rack1 ($SYS) complete"
