#!/usr/bin/env bash

set -o errexit -o nounset -o pipefail

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

# Order of Bazel selection:
# 1. BAZEL_REAL: Use Bazel specified by Bazelisk
# 2. BIT_BAZEL_BINARY: Use Bazel specified by rules_bazel_integration_test.
# 3: bazel: Try to find Bazel on the PATH
#
# NOTE: Do not put BIT_BAZEL_BINARY first in the evaluation. It can lead to 
# recursive loop when using rules_bazel_integration_test.
bazel="${BAZEL_REAL:-${BIT_BAZEL_BINARY:-bazel}}"

# Generate a bazel script for rules_xcodeproj to use. This script ensures that
# the xcodeproj runner uses the Bazel that is under test. We configure the
# xcodeproj macro to find this generated bazel script.
bazel_for_xcodeproj="${script_dir}/bazel_for_xcodeproj"
cat >"${bazel_for_xcodeproj}" <<-EOF
#!/usr/bin/env bash

# NOTE: This file is generated by tools/bazel. It is used by the xcodeproj 
# macro.

set -o errexit -o nounset -o pipefail

# Use the Bazel binary that we specify.
bazel="${bazel}"

# Execute the Bazel command
"\${bazel}" "\${@}"
EOF
chmod +x "${bazel_for_xcodeproj}"

# Execute the command
"${bazel}" "${@}"
