#!/bin/sh

extract_git_version()
{
    PREVPWD="$PWD"
    cd "$1"
    if [ -d ./.git ] || git rev-parse --is-inside-work-tree > /dev/null 2> /dev/null
    then
        REV=$(git show --format=%H#%ci -s $(git rev-parse HEAD) |
                     sed -e 's/ .*//' -e 's/[0-9a-f]\{30\}#/#/' -e 's/-//g' \
                         -e 's/#/-/')
        X=$(git status -s -uno | sed -e 's/.*/X/' | uniq)
        echo $REV$X
    else
        echo "unknown"
    fi
    cd "$PREVPWD"
}

srcdir="${1:-.}"

if [ -e "$srcdir"/include/vgversion_dist.h ]
then
    cp "$srcdir"/include/vgversion_dist.h include/vgversion.h.tmp
else
    cat > include/vgversion.h.tmp <<EOF
/* Do not edit: file generated by auxprogs/make_or_upd_vgversion_h.
   This file defines VGGIT, used to report GIT revision
   when using command line options:  -v --version
   The produced VGGIT format is
      hhhhhhhhhh-YYYYMMDDX
   where hhhhhhhhhh is the first 10 characters of the HEAD commit
         YYYYMMDD is the commit date
         Trailing X is present if there are any (non untracked) modified files.
*/
#define VGGIT "$(extract_git_version .)"
EOF
fi

if [ -f include/vgversion.h ]
then
    # There is already a vgversion.h.
    # Update it only if we found a different and real git version
    if grep -q unknown include/vgversion.h.tmp ||
       cmp -s include/vgversion.h include/vgversion.h.tmp
    then
        rm -f include/vgversion.h.tmp
    else
        mv include/vgversion.h.tmp include/vgversion.h
    fi
else
    # There is no vgversion.h. Use the one just generated, whatever it is.
    mv include/vgversion.h.tmp include/vgversion.h
fi
