#!/bin/sh
#
#  A simple script to gather some build information and prepare
#  a little include file for the eurephiadm buildinfo command
#
#  GPLv2 only - Copyright (C) 2010 - 2012
#               David Sommerseth <dazo@users.sourceforge.net>
#
#  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; version 2
#  of the License.
#
#  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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#
#
builddate="`date -u`"
buildsystem="`uname -a`"
buildhost="`hostname`"

# Check if we're in a git tree
gitdir="`git rev-parse --git-dir 2> /dev/null`"
if [[ $? = 0 ]]; then
    # If we have a .git directory, presume the source is from a git tree
    branch=`git symbolic-ref HEAD`
    gitrev=`git rev-list ${branch} -1`
    buildsource="`git remote -v | awk '/^origin/{print $2; exit 0}'` (origin)"

    curdir=`pwd`
    srcroot="`dirname $gitdir`"
    cd $srcroot
    modfiles="`git status -s | awk 'BEGIN{modcount=0} /^[ ADM\?]([ ADM\?])/{ printf "         %s\\\n", $0; modcount += 1 } END{exit modcount}'`"
    modcount=$?
    cd $curdir
else
    # Otherwise, it's from a source tarball
    buildsource="tar.bz2"
fi

# Excract configure exectution
configurecall="$(egrep "^# (.*)configure " ../configure.log | cut -b3-)"

cat <<EOF > buildinfo.h
/* Generated automatically by $0 */
/* Do not edit manually          */
#define BUILDDATE "${builddate}"
#define BUILDSYSTEM "${buildsystem}"
#define BUILDHOST "${buildhost}"
#define BUILDSOURCE "${buildsource}"
#define BUILDCONFIGURE "${configurecall}"
EOF

if [[ -n "${gitrev}" ]]; then
    cat <<EOF >> buildinfo.h
#define GITDIR "${gitdir}"
#define BUILDBRANCH "${branch}"
#define BUILDGITREV "${gitrev}"
#define MODIFIEDCOUNT ${modcount}
#define MODIFIEDFILES "${modfiles}"
EOF
fi
