#!/usr/bin/env bash

set -o pipefail

GIT_ROOT=$(cd "${BASH_SOURCE%/*}" && git rev-parse --show-toplevel)
cd "${GIT_ROOT}" || exit 1

GO_VERSION=$(yq '.variables.GO_VERSION' .gitlab/ci/_common.gitlab-ci.yml)
GOLANGLINT_VERSION=$(yq '.variables.GOLANGLINT_VERSION' .gitlab/ci/_common.gitlab-ci.yml)
ERRORS=0

# Add a line here for every file that pins a Go version, so a new drift spot
# fails this job instead of surfacing later as an unrelated CI failure.
check() {
    local description=$1
    local file=$2
    local pattern=$3

    if ! grep -qF "${pattern}" "${file}"; then
        echo "✖ ${description}: expected to find '${pattern}' in ${file}"
        ((ERRORS++))
    fi
}

check "mise.toml golang version" mise.toml "golang = \"${GO_VERSION}\""
check "go.mod go directive" go.mod "go ${GO_VERSION}"
check "docs/development/_index.md Go version" docs/development/_index.md "${GO_VERSION}"
check ".gitlab/duo/agent-config.yml runner-linters image tag" .gitlab/duo/agent-config.yml "${GOLANGLINT_VERSION}-go${GO_VERSION}"

if [ "${ERRORS}" -ne 0 ]; then
    echo "✖ ${ERRORS} Go version mismatch(es) found. Update the file(s) above to match GO_VERSION=${GO_VERSION} (from .gitlab/ci/_common.gitlab-ci.yml)."
    echo "  Run 'scripts/check-go-version-consistency' locally to re-check."
    exit 1
else
    echo "✔ All Go version references match GO_VERSION=${GO_VERSION}"
    exit 0
fi
