#!/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}}

# SHIM:
# Called from legacy bamboo plans with legacy environment.
# Check if ./ci/zimbeast/bamboo_entrypoint.sh exists. If so use the legacy
# methods, otherwise convert to the new environment and trigger the new script

. ./scripts/vehicle/common.sh

BAMBOO_ENTRYPOINT=./bamboo_entrypoint.sh
if [ -f ci/zimbeast/${BAMBOO_ENTRYPOINT} ]; then
  # ----------------------------
  #         LEGACY
  # ----------------------------
  # If the bamboo_entrypoint.sh script exists in the driving repo, then this
  # is an old version. Use that script to trigger the test.
  cd ci/zimbeast
  . ${BAMBOO_ENTRYPOINT}
  exit 0
else
  # ----------------------------
  #         TALOS
  # ----------------------------
  # PARTIAL support for Talos testing via this shim. You should be calling the
  # new integration_test_TALOS.sh

  # Handle test-type
  TEST_TYPE=$(echo "${bamboo_shortPlanName}${bamboo_shortJobName}" | grep -oi -E "logbot|zimbot|stardash|teleop" | head -n 1 | tr "[:upper:]" "[:lower:]")
  case $TEST_TYPE in
    logbot)
      TEST="ci/zimbeast/test_scripts/logplay_integration/test_logplay.py"
      export bamboo_slack_channel="#zb_logplay_results"
      ;;
    zimbot)
      TEST="ci/zimbeast/test_scripts/zimbot_sim/test_zimbot.py"
      export bamboo_slack_channel="#ci-zimbot-manual"
      ;;
    stardash)
      TEST="ci/zimbeast/test_scripts/stardash/test_stardash.py"
      export bamboo_slack_channel="#stardash-logbot"
      ;;
    teleop)
      TEST="ci/zimbeast/test_scripts/teleop/test_teleop_logplay.py"
      export bamboo_slack_channel="#ci-teleop-manual"
      ;;
    *)
      echo "Invalid test type: ${TEST_TYPE}"
      exit 1
      ;;
  esac

  # Work as-is: zstart_opts, zstart_path, num_successes, num_retries

  # CHUM URI
  if [[ ! -z ${bamboo_chum_uri:-} ]]; then
    export bamboo_test_param_chum_uri=$bamboo_chum_uri
  fi

  export bamboo_test=$TEST

  ci/zimbeast/run_hil_test.py --bamboo
  exit 0
fi
