#!/bin/sh
#
# generate-git-info: build the file git-info.h used (mainly) by STklos -V
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
# USA.
#
#           Author: Erick Gallesio [eg@stklos.net]
#    Creation date: ???

summary='#define GIT_SUMMARY "()"';     # default value

git_version=$(git --version 2>/dev/null || true)

if [ "$git_version" != "" ]
then
    # Git is installed
    if [ "$(git rev-parse --is-inside-work-tree 2>/dev/null)" = "true" ]
    then
        # We are in a git tree

        # detect git tag, branch, commit, and wether the repository is dirty
        # when not in a git repository, all the strings will be empty,
        # and STklos will be able to detect this.
        git_tag="$(git describe --tags --abbrev=0 2>/dev/null || true)"
        git_branch="$(git rev-parse --abbrev-ref HEAD 2>/dev/null || true)"
        git_commit="$(git rev-parse --short HEAD 2>/dev/null || true)"
        git_modified="$(git diff-index --name-only HEAD 2>/dev/null |  xargs -n 1 printf ' \\"%s\\"')"
        git_patch="$(git describe --tags | sed -Ee 's/.*-(.*)-.*/\1/') || true"

        tmp1="#:branch \\\"$git_branch\\\" #:commit \\\"$git_commit\\\""
        tmp2="#:tag \\\"$git_tag\\\" #:modified ($git_modified) #:patch \\\"$git_patch\\\""
        summary="#define GIT_SUMMARY \"($tmp1 $tmp2)\""
    fi
fi

echo "$summary" > new-git-info.h

# Eventually update the git-info.h file
if cmp --quiet new-git-info.h git-info.h 2>/dev/null
then
    rm new-git-info.h
else
    echo "*** Updating git-info.h"
    mv new-git-info.h git-info.h
fi
