#!/usr/bin/bash

# Copyright Advanced Micro Devices, Inc.
#
# SPDX-License-Identifier: MIT

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(cd "${script_dir}/.." && pwd)"

# helpers
is_git_repo=false
if git -C "$repo_root" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
    is_git_repo=true
fi

# 1) VERSION file (preferred over git describe)
version_file="${script_dir}/VERSION"
if [ -f "$version_file" ]; then
    head -1 "$version_file"
    exit
fi

# 2) git tag + commits ahead + 10-char hash
if $is_git_repo; then
    # Match tags like 8.5.0.K, 8.4.0.K-rc1, 8.5.0.K-dev
    desc="$(git -C "$repo_root" describe --tags --long --abbrev=10 --match '[0-9]*.[0-9]*.[0-9]*.K*' 2>/dev/null || true)"
    if [ -n "$desc" ]; then
        # Check if it's a formal tag (X.Y.Z.K without suffix) and we're exactly on it (0 commits ahead)
        if echo "$desc" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+\.K-0-g[0-9a-f]{10}$'; then
            # For formal tags, strip the -0-<hash> suffix
            desc="$(echo "$desc" | sed -E 's/-0-g[0-9a-f]{10}$//')"
        else
            # For non-formal tags or commits ahead, keep commits and hash
            desc="$(echo "$desc" | sed -E 's/-g([0-9a-f]{10})$/-\1/')"
        fi
        echo "$desc"
        exit
    fi
fi

# 3) Git hash only -> 0.0.0.K-g<hash>
if $is_git_repo; then
    shash="$(git -C "$repo_root" rev-parse --short=10 HEAD 2>/dev/null || true)"
    if [ -n "$shash" ]; then
        echo "0.0.0.K-${shash}"
        exit
    fi
fi

# 4) Default
echo "Cannot detect tag, git hash or VERSION file, using fallback version 0.0.0.K" 1>&2
echo "0.0.0.K"
