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

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_logbot_branch:-${bamboo_repository_revision_number}}

. ./scripts/vehicle/common.sh

cd ci/zimbeast

BAMBOO_ENTRYPOINT=./bamboo_entrypoint.sh
if [ -f ${BAMBOO_ENTRYPOINT} ]
then
  # If the bottom half script exists in the driving repo, use that.
  # Otherwise fall through to the original integration script below.
  . ${BAMBOO_ENTRYPOINT}
  exit 0
fi

# Test Type and test context can be inferred from the plan name or job name
TEST_TYPE=$(echo "${bamboo_shortPlanName}${bamboo_shortJobName}" | grep -oi -E "logbot|zimbot|stardash|teleop" | head -n 1 | tr "[:upper:]" "[:lower:]")
TEST_CONTEXT=$(echo "${bamboo_shortPlanName}${bamboo_shortJobName}" | grep -oi -E "master|manual|local" | head -n 1 | tr "[:upper:]" "[:lower:]")

# Not all jobs specify manual, but if master is not explicitly specified,
# consider it manual.
if [ -z "$TEST_CONTEXT" ]
then
  TEST_CONTEXT=manual
fi

case $TEST_TYPE in
  logbot | stardash | teleop)
    CHUM_URI="--chum-uri ${bamboo_chum_uri:-$bamboo_logbot_default_chum_uri}"
    LAUNCH_VISION="--launch-vision ${bamboo_launch_vision:-true}"
    ;;
  zimbot)
    CHUM_URI=""
    LAUNCH_VISION=""
    ;;
  *)
    echo "Invalid test type: ${TEST_TYPE}"
    exit 1
    ;;
esac

# This is to accomodate changing the name of test.py
for script_name in test.py run_hil_test.py
do
  if [ -r "${script_name}" ]
  then
    TEST_SCRIPT="${script_name}"
    break
  fi
done

python ${TEST_SCRIPT} --bamboo-branch \
  --test-type ${TEST_TYPE} \
  --test-context ${TEST_CONTEXT} \
  ${CHUM_URI} \
  --zstart-opts "${bamboo_zstart_options:-}" \
  --num-successes "${bamboo_num_successes:-1}" \
  --num-retries "${bamboo_num_retries:-0}" \
  ${LAUNCH_VISION}
