#!/bin/sh

#
# Reload defaults
#

BUILD=sdk
CONFIG=sdk/config.h

if test -f config.cache ; then
	. ./config.cache
fi
echo -n >config.cache

if test -f config.pkg ; then
	. ./config.pkg
fi

#
# Load bindings
#

if test -f config.pkg ; then
	. ./config.pkg
fi

if test -f config.make ; then
	echo -n >config.make
fi

if test -f $CONFIG ; then
	echo -n >$CONFIG
fi

if test -f $BUILD/bin/config.sub ; then
	. $BUILD/bin/config.sub
fi

BIND_OPTS='host'

if test -z "$CONFIG_HOST" ; then
	if test -d /usr/local/include ; then
		CONFIG_HOST=/usr/local
	fi
	if test -d /usr/include ; then
		CONFIG_HOST=/usr
	fi
fi

opt_host() {
	CONFIG_HOST="$1"
	return 0
}

if test ! -z "$BIND" ; then
	for bind in $BIND ; do
		if test -d $BUILD/$bind ; then
			. $BUILD/$bind/bind.conf
		else
			. $BUILD/bin/$bind.bind
		fi
	done
fi

# 
# Parse command line arguments.
#
err=''

if test ! -z "$CONFIG_FLAGS" ; then
	for arg in $CONFIG_FLAGS ; do
		for opt in $BIND_OPTS ; do
			case "$arg" in
			$opt=* | -$opt=* | --$opt=* )
				opt_$opt `echo "$arg" | sed 's/[-_a-zA-Z0-9]*=//'`
				break
				;;
			esac
		done	
	done
fi


if test ! -z "$*" ; then
	for arg in $* ; do
		err=$arg
		for opt in $BIND_OPTS ; do
			case "$arg" in
			$opt=* | -$opt=* | --$opt=* )
				opt_$opt `echo "$arg" | sed 's/[-_a-zA-Z0-9]*=//'`
				err=''
				break
				;;
			esac
		done	
		if test ! -z "$err" ; then
			break
		fi
	done
fi

CONFIG_FLAGS=''

if test ! -z "$err" ; then
	echo "config: $err: invalid option."
	echo 
	echo "Valid Options:" 
	echo -n >config.help
	if test ! -z "$BIND" ; then
		for use in $BIND ; do
			if test -f $BUILD/$use/help.conf ; then
				cat $BUILD/$use/help.conf >>config.help
			fi
			if test -f $BUILD/bin/$use.help ; then
				cat $BUILD/bin/$use.help >>config.help
			fi
		done
		sort <config.help
		rm -f config.help
	fi
	exit -1
fi

echo "#ifndef	__CONFIG_H__" >>$CONFIG
echo "#define	__CONFIG_H__" >>$CONFIG

CONFIG_LIBS=""

if test ! -z "$BIND" ; then
	for bind in $BIND ; do
		if test -f $BUILD/$bind/make.conf ; then
			. $BUILD/$bind/make.conf
			CONFIG_LIBS='-l'$bind' '"$CONFIG_LIBS"
			if test -f $BUILD/$bind/Makefile.in ; then
				MAKEFILES="$MAKEFILES"' '$BUILD/$bind/Makefile
			fi
		else
			if test -f $BUILD/bin/$bind.make ; then
				. $BUILD/bin/$bind.make
			fi
		fi
	done
fi

if test ! -z "$CONFIG_LIBS" ; then
	echo "LIBS=$CONFIG_LIBS" >>config.make
fi

if test ! -z "$MAKEFILES" ; then
	for makefile in $MAKEFILES ; do
		cat config.make >$makefile
		cat $makefile.in >>$makefile
	done
fi

echo "#endif" >>$CONFIG


if test -z "$CONFIG_CACHE" ; then
	CONFIG_CACHE='config.cache'
	CONFIG_FLAGS=''
else
	CONFIG_FIRST=''
fi

echo "CONFIG_CACHE="$CONFIG_CACHE >>config.cache

if test -f conftest.c ; then
	rm -f conftest.c
fi

if test -f conftest.o ; then
	rm conftest.o
fi

if test ! -z "$CONFIG_FIRST" ; then
	$CONFIG_FIRST
fi

