#!/bin/bash

# Copyright (c) Advanced Micro Devices, Inc. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
# THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

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) git tag + commits ahead + 10-char hash
if $is_git_repo; then
    # Expect tags like 8.5.0.K, 8.5.0.K-dev, 8.4.0.K-rc1
    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

# 2) VERSION file + git hash
version_file="${script_dir}/VERSION"
if [ -f "$version_file" ]; then
    base_ver="$(head -1 "$version_file")"
    if $is_git_repo; then
        shash="$(git -C "$repo_root" rev-parse --short=10 HEAD 2>/dev/null || true)"
    else
        shash=""
    fi
    if [ -n "$shash" ]; then
        echo "${base_ver}-${shash}"
    else
        echo "$base_ver"
    fi
    exit
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"
