#!/usr/bin/env bash

# This command is used by bazel as the workspace_status_command
# to implement build stamping with git information.

set -o errexit
set -o nounset
set -o pipefail

# NOTE:
# Building the `gitlab-agent` project, that is KAS and agentk,
# is supported in multiple contexts.
# For official KAS releases happening in CNG and Omnibus, the binaries
# are built from an archive (non-git) source tree.
# Whereas official agentk releases are happening in the canonical gitlab-agent
# repository where it is built from a git source tree.
# Therefore, we use the following logic to determine the release `VERSION`:
# - `version` is the version of the release. It refers to the `VERSION` file.
# - `git_ref` is the Git reference of the release.
#   - If the environment variable `GIT_REF` is set, it'll be used.
#   - If the environment variable `GIT_REF` is not set, but `GIT_COMMIT` is set, it'll be used.
#   - Otherwise, it will try to get the commit SHA from Git if the build is from within a Git repository.
#   - If all the above fail, an empty Git reference is used as a fallback.
#   If `git` is not available, it will fallback to the `version`.
version="v$(cat ./VERSION)"
if [[ -n "${GIT_REF:-}" ]]; then
  git_ref=${GIT_REF}
elif [[ -n "${GIT_COMMIT:-}" ]]; then
  git_ref=${GIT_COMMIT}
elif git rev-parse --is-inside-work-tree &> /dev/null; then
  git_ref=$(git rev-parse HEAD)
else
  git_ref=""
fi

# Prefix with STABLE_ so that these values are saved to stable-status.txt
# instead of volatile-status.txt.
# Stamped rules will be retriggered by changes to stable-status.txt, but not by
# changes to volatile-status.txt.
# See https://docs.bazel.build/versions/master/user-manual.html#flag--workspace_status_command
# DO NOT CHANGE ORDER OR ADD ANYTHING HERE without also adjusting column numbers in the "version" target in the makefile.
# The names of the values must match the names in cmd/cmd.bzl#L9.
cat <<EOF
STABLE_BUILD_VERSION ${version}
STABLE_BUILD_GIT_REF ${git_ref}
EOF
