#!/bin/bash
#
# Copyright 2018 The Bazel Authors
# Copyright 2022 Stéphane Caron
# Copyright 2023 Inria
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

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}
