#!/bin/bash
#
# Copyright 2018 The Bazel Authors
# Copyright 2022 Stéphane Caron
# Copyright 2023 Inria
# SPDX-License-Identifier: Apache-2.0

set -euo pipefail

toolchain_name=""

while getopts "t:h" opt; do
  case "$opt" in
    "t") toolchain_name="$OPTARG";;
    "h") echo "Usage:"
       echo "-t - Toolchain name to use for testing; default is llvm_toolchain"
       exit 2
       ;;
    "?") echo "invalid option: -$OPTARG"; exit 1;;
  esac
done

os="$(uname -s | tr "[:upper:]" "[:lower:]")"
readonly os

# Value of BAZELISK_GITHUB_TOKEN is set as a secret in the GitHub workflow.
readonly BAZELISK_VERSION="v1.16.0"
readonly BAZELISK_URL="https://github.com/bazelbuild/bazelisk/releases/download/${BAZELISK_VERSION}/bazelisk-${os}-amd64"

readonly CURDIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null && pwd)

bazel="${CURDIR}/bazel"
readonly bazel

if [ -f "${bazel}" ]; then
    echo "Using existing Bazel binary from ${bazel}..."
else
    echo "Downloading Bazel binary from ${BAZELISK_URL}..."
    curl -L -Sf --progress-bar -o "${bazel}" "${BAZELISK_URL}"
    chmod a+x "${bazel}"
fi

set -x
"${bazel}" version
"${bazel}" ${@:1:99}
