#!/bin/sh

# SPDX-License-Identifier: GPL-3.0-only

package="$1"
version_file="$2"

ver='unnamed_version'
# First try git, then gitweb, then default.
if [ -e '.git' -o -e '../.git' ]; then
	git_ver=$(git describe --abbrev=4 HEAD 2>/dev/null)
	[ -z "$git_ver" ] && git_ver="$ver"
	# update stat information in index to match working tree
	git update-index -q --refresh > /dev/null
	# if there are differences (exit code 1), the working tree is dirty
	git diff-index --quiet HEAD || git_ver=$git_ver-dirty
	ver=$git_ver
elif [ "${PWD%%-*}" = $package- ]; then
	ver=${PWD##*/$package-}
fi
ver=${ver#v}

echo "$ver"
[ -z "${version_file}" ] && exit 0
# update version file if necessary
content="const char *${package}_version(void) {return \"$ver\";};"
[ -r "$version_file" ] && echo "$content" | cmp -s - $version_file && exit 0
echo "$content" > $version_file
