#! /bin/sh

##  Create version.h from INN version information.
##
##  Makefile.global contains the INN version number and extra version
##  information (if any).  This is passed to use by lib/Makefile as our
##  first and second arguments.  Print a header file suitable for use
##  as inn/version.h on stdout.

version="$1"
extra="$2"
string="INN $version"

if [ x"$extra" = x"prerelease" ]; then
    # Default date is the build date.
    date=$(date +%Y%m%d)

    # Ensure a reproducible build when the source code has not changed, and is
    # built from a Git repository.
    if [ -n "$(command -v git 2>/dev/null)" ]; then
        LAST_COMMIT=$(git log -1 --pretty=%cd --date=format:%Y%m%d 2>/dev/null)
        if [ -n "$LAST_COMMIT" ]; then
            date="$LAST_COMMIT"
        fi
    fi

    extra="$date $extra"
fi

if [ -n "$extra" ]; then
    string="$string ($extra)"
fi

major=$(echo "$version" | cut -d. -f1)
minor=$(echo "$version" | cut -d. -f2)
patch=$(echo "$version" | cut -d. -f3)

cat <<EOF
/* Automatically generated by mkversion, edit Makefile.global to change. */

#ifndef INN_VERSION_H
#define INN_VERSION_H 1

#define INN_VERSION_MAJOR $major
#define INN_VERSION_MINOR $minor
#define INN_VERSION_PATCH $patch
#define INN_VERSION_EXTRA "$extra"
#define INN_VERSION_STRING "$string"

#endif /* INN_VERSION_H */
EOF
