#!/usr/bin/env bash

# this script requires bamboo to use an ssh task with the following commands:
#  git fetch and checkout is done in bamboo for correct run_hil_tester.sh file
# 1| cd /home/itloaner/driving
# 2| git fetch -p
# 3| git checkout ${bamboo.repository.revision.number}
# 4| ./firmware/legacy/hil_tester/run_hil_tester.sh ${bamboo.repository.revision.number} ${bamboo.buildResultsUrl}

# Enable unofficial bash strict mode.
set -euo pipefail

function run_hil_tests() {
  all_testing_targets=$(python ci/affected_targets.py origin/master 2>&1)
  diff_from_master=$(git diff HEAD origin/master 2>&1)

  # only run tests if there are changes in primary/safety or on master branch
  if [[ $all_testing_targets == *"firmware/legacy/primary"* ]] || \
     [[ $all_testing_targets == *"firmware/legacy/safety"* ]] || \
     [[ $all_testing_targets == *"firmware/legacy/common"* ]] || \
     [[ $all_testing_targets == *"firmware/legacy/hil_tester"* ]] || \
     [[ $all_testing_targets == *"third_party/ChibiOS"* ]] || \
     [[ $all_testing_targets == *"vehicle/common/dbc"* ]] || \
     [[ $all_testing_targets == *"vehicle/stdr_libraries/zoox_can"* ]] || \
     [[ $diff_from_master == "" ]]; then
    # setup computer
    ./scripts/setup/setup.sh dev --no-ask-pass
    source /home/itloaner/driving/scripts/shell/zooxrc.sh

    # flush can buffer
    sudo ip link set can0 down
    sudo ip link set can0 up
    sudo ip link set can1 down
    sudo ip link set can1 up
    sudo ip link set can2 down
    sudo ip link set can2 up

    # clean, and build ECU's
    bazel clean --expunge
    bazel build firmware/legacy/primary:primary
    bazel build firmware/legacy/safety:safety
    bazel build firmware/legacy/naughty_primary:naughty_primary

    # hard reset + update primary and safety
    python firmware/legacy/hil_tester/update_ecu.py primary
    python firmware/legacy/hil_tester/update_ecu.py safety

    # test to make sure both ecu's can flash properly
    python firmware/legacy/hil_tester/self_flash_test.py

    # Run appropriate tests
    bazel test firmware/legacy/hil_tester:fmea_hil_test --test_output=all
    bazel test firmware/legacy/hil_tester:user_error_hil_test --test_output=all
    bazel test firmware/legacy/hil_tester:autonomous_odometer_hil_test --test_output=all
    bazel test firmware/legacy/hil_tester:intervention_reporting_hil_test --test_output=all

    # flash naughty primary and run safety unit tests
    python firmware/legacy/hil_tester/update_ecu.py naughty_primary
    bazel test firmware/legacy/hil_tester:safety_only_test --test_output=all
  else
    echo "no changes to firmware detected, skipping tests"
  fi
}

run_hil_tests
