#!/usr/bin/env bash
set -euo

# Check if the Cinder job that started this has been cancelled
if [[ -v bamboo_cinder_build_id && -v bamboo_cinder_job_name ]]; then
    set +e
    result=`curl -s -X GET --header "Accept: application/json" "https://ci-builds.zooxlabs.com/v1/builds/${bamboo_cinder_build_id}" | jq ".jobs[] | select(.name==\"${bamboo_cinder_job_name}\") |  .result"`
    set -e
    if [[ $result == *"TERMINATED"* ]]; then
      echo "Skipping test because corresponding cinder build ${bamboo_cinder_build_id} / job ${bamboo_cinder_job_name} has already been cancelled"
      exit 1
    else
      echo "Running cinder build ${bamboo_cinder_build_id} / job ${bamboo_cinder_job_name} with current state ${result}"
    fi
else
  echo "Skipping cinder job check because this is not a cinder job"
fi

# Entry point for automation agents to call run_hil_test.py
# Currently only supports being called by bamboo.

export LC_ALL="en_US.UTF-8"

export ZOOX_WORKSPACE_ROOT=/home/zoox/driving
cd ${ZOOX_WORKSPACE_ROOT}

# Checkout test entrypoint branch (this may be different from deploy branch)
git fetch origin
git stash
git checkout ${bamboo_repository_revision_number}

ci/zimbeast/run_hil_test.py --bamboo
