#!/bin/bash

# Caching of Git tagging information for version archives that don't contain
# the Git repo information.

set -e

o() {
	if [[ $(git tag | grep -E '^'$1'$') == "$1" ]] ; then
		echo $1
		return 0
	fi

	git describe $1 2>/dev/null >/dev/null
	local ver prefix major minor patch num hash
	ver=$(git describe $1)

	if [[ "$ver" =~ ^(v?)([0-9]+)\.([0-9]+)\.([0-9]+)-([0-9]+)-(g[0-9a-f]+)$ ]]; then
		prefix="${BASH_REMATCH[1]}"
		major="${BASH_REMATCH[2]}"
		minor="${BASH_REMATCH[3]}"
		patch="${BASH_REMATCH[4]}"
		num="${BASH_REMATCH[5]}"
		hash="${BASH_REMATCH[6]}"

		# Bump the patch number
		patch=$(($patch + 1))

		# Rebuild string with ~ instead of the first -
		ver="${prefix}${major}.${minor}.${patch}~prerelease-${num}-${hash}"
	fi

	echo "${ver}"
	err=$?
	return ${err}
}

if [[ "$2" == "save" ]] ; then
	o $1 > $3
else
	if [[ -e .git-version-save ]] ; then
		cat .git-version-save
	else
		o $1
	fi
fi
