#!/bin/sh

#configure - FireMake configuratin script
#Copyright (C) 2002 Ian Gulliver
#
#This program is free software; you can redistribute it and/or modify
#it under the terms of version 2 of the GNU General Public License as
#published by the Free Software Foundation.
#
#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

VERSION="1.9.9"

ECHO=echo
if test -f /usr/ucb/echo; then
	ECHO=/usr/ucb/echo
fi

disp() {
	if test ! "$LASTN" = "1"; then
		$ECHO -n "$PREPEND" 1>&2
	fi
	LASTN="0"
	$ECHO "$1" 1>&2
}

dispn() {
	if test ! "$LASTN" = "1"; then
		$ECHO -n "$PREPEND" 1>&2
	fi
	LASTN="1"
	$ECHO -n "$1" 1>&2
}

module() {
	test -f firemake/$1
}

PHASES="library init config header makefile"

disp "FireMake v$VERSION starting....";
disp

disp "= Starting dependency check ="
for MODULE in `ls firemake`; do
	REQ=`grep "^#require " firemake/$MODULE 2>/dev/null | cut -d ' ' -f 2`;
	if test "$?" = "0"; then
		# module has requirements, check that these modules exist
		for FILE in $REQ; do
			if test ! -f firemake/$FILE; then
				disp "	Module $MODULE requires module $FILE which is not present; aborting"
				exit 1;
			fi
		done
	fi
done
disp "= Done with dependency check ="
disp


for PHASE in $PHASES; do
	disp "= Starting $PHASE phase ="
	case "$PHASE" in
		init)
			exec > /dev/null
			;;
		config)
			exec > /dev/null
			;;
		header)
			exec > firemake.h
			;;
		makefile)
			exec > Makefile
			;;
	esac
	NEWDATA="1"
	while test "$NEWDATA" = "1"; do
		NEWDATA="0"
		for MODULE in `ls firemake`; do
			$ECHO "$DID " | grep " ${PHASE}_${MODULE} " > /dev/null
			if test ! "$?" = "0"; then
				grep "^#phase $PHASE" firemake/$MODULE > /dev/null 2>/dev/null
				if test "$?" = "0"; then
					SAT="1"
					DEPS=`grep "^#after ${PHASE}_" firemake/$MODULE | cut -d ' ' -f 2`;
					if test "$?" = "0"; then
						#runtime dependencies
						for DEP in $DEPS; do
							$ECHO "$DID " | grep " ${DEP} " > /dev/null
							if test ! "$?" = "0"; then
								SAT="0"
							fi
						done
					fi
					if test "$SAT" = "1"; then # dependencies satisfied
						PREPEND="		"
						. firemake/$MODULE
						unset PREPEND
						DID="$DID ${PHASE}_${MODULE}"
						NEWDATA="1"
					fi
				fi
			fi
		done
	done
	disp "= Done with $PHASE phase ="
	disp
done

disp "Finished configuring. Now just run \"make\""
