#!/usr/bin/env bash

set -o errexit -o nounset -o pipefail

# rules_xcodeproj executes some Bazel commands. We need to tell it which
# version to use. Ideally, we would pass the path to the binary.  For now, we
# will count on the fact that it expects to find `bazel` in the PATH.
if [[ -n "${BIT_BAZEL_BINARY:-}" ]]; then
	bazel="${BIT_BAZEL_BINARY}"
	tmp_dir="$(mktemp -d)"
	ln -s "${BIT_BAZEL_BINARY}" "${tmp_dir}/bazel"
	export PATH="${tmp_dir}:${PATH}"
else
	bazel="bazel"
fi

print_and_run() {
	local cmd="${1}"
	shift 1
	printf >&2 "======================\n%s: %s %s\n======================\n" \
		"$(basename "${BASH_SOURCE[0]}")" "$(basename "${cmd}")" "$*"
	"${cmd}" "$@"
}

# Remove the temp directory if we created it.
cleanup() {
	if [[ -n "${tmp_dir:-}" ]]; then
		rm -rf "${tmp_dir}"
	fi
}
trap cleanup EXIT

# Generate Swift external deps and update build files
print_and_run "${bazel}" run //:tidy

# Generate the Xcode project
print_and_run "${bazel}" run //:xcodeproj

# Big clean. We perform the expunge to ensure that SPM commands work properly
# when Bazel is executed by Xcode projects generated by rules_xcodeproj.
# Related issue:
# https://github.com/MobileNativeFoundation/rules_xcodeproj/issues/2355
print_and_run "${bazel}" clean --expunge

# GH1678: Enable this once the underlying build failure is addressed.
# # Build the FooTests scheme in the Xcode project
# print_and_run xcodebuild -project App.xcodeproj -scheme FooTests

# Ensure that it builds and tests pass
print_and_run "${bazel}" test //...
