#!/bin/bash

to_ver() {
	VN=$1
	#drop leading 'v' out of the version so its a pure number
	if [ ${VN:0:1} = "v" ]; then
			VN=${VN:1}
	fi
	echo $VN
}

dirty() {
	VN=$(to_ver $1)
	git update-index -q --refresh
	if test -z "$(git diff-index --name-only HEAD --)"; then
		echo "$VN"
	else
		echo "${VN}.dirty"
	fi
}

DEF_VER=61.2

LF='
'

# First see if there is a version file (included in release tarballs),
# then try git-describe, then default.
if test -f version; then
	VN=$(cat version) || VN="$DEF_VER"
elif test -d ${GIT_DIR:-.git} -o -f .git &&
	VN=$(git describe --match "v[0-9]*" --abbrev=7 HEAD 2>/dev/null) &&
	case "$VN" in
	*$LF*) (exit 1) ;;
	v[0-9]*)
		VN="$(dirty $VN)"
	esac; then
	VN=$(echo "$VN" | sed -e 's/-/./g');
else
	read COMMIT COMMIT_SUBJECT <<EOF
	$(git log --oneline --abbrev=8 -n1 HEAD 2>/dev/null)
EOF
	if [ -z $COMMIT ]; then
		VN="${DEF_VER}+"
	else
		VN="$(dirty ${DEF_VER}.git$COMMIT)"
	fi
fi

echo $VN
