#!/bin/sh

devflag=""
dirtyflag=""
# set the version from tags
tag="$(git describe --exact-match --tags 2>/dev/null)"
if [ -n "$tag" ]; then
	# we are exactly on a tag (ex: 2015_09_10_08_51_version_1.6.7)
	# so we have just to extract the version
	version="$(echo "$tag" | sed "s/^.*_//")"
else
	# we are not on a tag.
	# In this case, we want to have the previous tag version plus "dev" string
	# and the number of commits
	# git describe format is tag-x-gsha1
	tag="$(git describe --long --tags 2>/dev/null)"
	if [ -n "$tag" ]; then
		version="$(echo "$tag" | sed "s/^.*_\(.*\)-[0-9]\+-g[^-]\+$/\1/")"
		nbcommit="$(echo "$tag" | sed "s/^.*_.*-\([0-9]\+\)-g[^-]\+$/\1/")"
		commit="$(echo "$tag" | sed "s/^.*_.*-[0-9]\+-g\([^-]\+\)$/\1/")"
		devflag="-dev"
	else
		nbcommit=0
		version="$(git log -1 --pretty="format:%h")"
	fi
fi

dirtyflag=$(git diff-index --name-only HEAD)
if [ -n "$dirtyflag" ]; then
	flag="-dirty"
else
	flag="$devflag"
fi

[ "$nbcommit" -eq "$nbcommit" ] 2>/dev/null || nbcommit=0

printf "%s%s" "${version}" "${flag}"
if [ "$nbcommit" -ne 0 ]; then
	printf "%03d_%s" "${nbcommit}" "${commit}"
fi
printf "\n"

# /* vim: set noai ts=8 sw=8: */
