#!/bin/bash
# $Id$
#
# Checkpkgs verifies that the directories listed in Makefile.am are available
# and removed any that are not found.  This is required so that that
# autoreconf works properly.
#

OLDSUBDIRS="$(grep ^SUBDIRS Makefile.am)"
DIRS=$(echo $OLDSUBDIRS | cut -f2- -d= | cut -f1 -d#)
echo "Packages listed: $DIRS"
remake="no"

for D in $DIRS ; do
	echo -n "Checking $D..."
	if [ -d $D -a -f $D/Makefile.am ]; then
		echo "found and ready"
		SUBDIRS="$SUBDIRS $D"
	else
		echo "not found or ready"
		remake="yes"
		MISSING="$MISSING $D"
	fi
done

if [ "$remake" == "yes" ]; then
	if [ ! -f Makefile.org ]; then
		echo "Saving Makefile.am to Makefile.org"
		cp Makefile.am Makefile.org
	fi
	echo "Updating Makefile.am to exclude missing packages"
	cat Makefile.am | sed -e "s/^SUBDIRS = .*/SUBDIRS = $SUBDIRS # previously: $DIRS/" > .tmp.$$
	mv .tmp.$$ Makefile.am

	if [ ! -f configure.org ]; then
		echo "Saving configure.ac to configure.org"
		cp configure.ac configure.org
	fi
	echo -n "Updating configure.ac to exclude missing packages"
	for D in $MISSING; do
		grep -v $D/Makefile configure.ac >.tmp.$$
		mv .tmp.$$ configure.ac
		echo -n "."
	done
	echo "done"
else
	echo "All packages are found"
fi

if [ -f VERSION ]; then
	. VERSION
	if [ -z "$MAJOR" -o -z "$MINOR" -o -z "$NAME" ]; then
		echo "ERROR: VERSION doesn't specified release version info"
	elif [ ! -f REV ]; then
		echo "ERROR: REV file not found; this release is faulty"
	elif [ -f gldcore/version.h ]; then
		. ./REV
		if [ -z "$BUILD" ]; then
			echo "ERROR: REV file does not specify BUILD"
		else
			echo -n "Updating gldcore/version.h with VERSION info... "
			echo "/* automatically created by $0 */" >.tmp.$$
			echo "" >>.tmp.$$
			echo "#ifndef _GRIDLABD_VERSION_H" >>.tmp.$$
			echo "#define _GRIDLABD_VERSION_H" >>.tmp.$$
			echo "" >>.tmp.$$
			echo "#define REV_MAJOR $MAJOR" >>.tmp.$$
			echo "#define REV_MINOR $MINOR" >>.tmp.$$
			echo "#define REV_PATCH $PATCH" >>.tmp.$$
			echo "#define COPYRIGHT \"Copyright (C) 2004-$(date +'%Y')\\nBattelle Memorial Institute\\nAll Rights Reserved\"" >>.tmp.$$
			echo "#ifdef WIN32 " >>.tmp.$$
			echo "#define BUILD \"\$Revision: $BUILD \$\"" >>.tmp.$$
			echo "#else" >>.tmp.$$
			echo "#include \"build.h\"">>.tmp.$$
			echo "#endif" >>.tmp.$$
			echo "#define BUILDNUM (atoi(BUILD+11))" >>.tmp.$$
			echo "#define BRANCH \"$NAME\"" >>.tmp.$$
			echo "" >>.tmp.$$
			echo "#endif" >>.tmp.$$
#			grep BRANCH gldcore/version.h >>.tmp.$$
			mv .tmp.$$ gldcore/version.h
			echo "done"
		fi
	else
		echo "ERROR: gldcore/version.h not found and couldn't be updated"
	fi	
fi

echo "You may proceed with autoreconf -isf"
