#! /usr/bin/env bash

# Copyright (c) 2024 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

set -euo pipefail

if [ $# -eq 1 ]; then
    OVERRIDE_VERSION=$1
fi

# We always run from splice-root, to make sure we are using Splice commit hashes,
# and not those of a repo that submodules Splice.
cd "${SPLICE_ROOT}"

sha=$(git rev-parse HEAD)

if [ -n "${OVERRIDE_VERSION-}" ]; then
    echo "${OVERRIDE_VERSION}"
    exit 0
fi

# Always use the release version on release branches.
release_version=$("${SPLICE_ROOT}"/build-tools/get-release-if-on-release-branch.sh)
if [ -n "${release_version-}" ]; then
    echo "${release_version}"
    exit 0
fi

set +e
if ! prefix=$(git show "$sha":VERSION 2>&1); then
    prefix=$(cat "${SPLICE_ROOT}/VERSION")
fi

set -e
git_commit_message=$(git log -1 --pretty=format:%B "$sha")
if [[ $git_commit_message == *"[release]"* ]]; then
    # release commit - no suffixes
    echo "$prefix"
    exit 0
fi

commit_date=$(git log -n1 --format=%cd --date=format:%Y%m%d "$sha")
number_of_commits=$(git rev-list --count "$sha")
commit_sha_8=$(git log -n1 --format=%h --abbrev=8 "$sha")

if [ -n "${SPLICECLUSTER_STATIC_DIRTY_VERSION:-}" ]; then
    if [ -n "${CI:-}" ]; then
        >&2 echo "SPLICECLUSTER_STATIC_DIRTY_VERSION and CI must not be set together"
        exit 1
    fi
    echo "$prefix-${USER}-dirty"
    exit 0
fi

user_suffix=""
if [ -z "${CI:-}" ]; then
    user_suffix="-${USER}"
fi

dirty_suffix=""
if ! (env-bool CI_IGNORE_DIRTY_REPO) && [[  $(git diff --stat) != '' || $(git diff --cached) != '' ]]; then
    if [ -z "${CI:-}" ]; then
        dirty_suffix="-dirty"
    else
        >&2 echo "Repo was dirty on CI"
        >&2 git status
        >&2 git --no-pager diff --cached
        exit 1
    fi
fi

echo "$prefix$user_suffix-snapshot.$commit_date.$number_of_commits.0.v$commit_sha_8$dirty_suffix"
