#!/bin/sh

set -e

archtypes="$1"	# list of architecture types
SRC="$2"	# source directory
SPATH="$3"	# path from $SRC to source dir
BASE="$4"	# path to base of build area
cwd=`pwd`

CONF_ARCH="$archtypes"
CONF_USER=`whoami`
CONF_DATE=`date`
CONF_HOST=`hostname`

echo "Configuring directory $cwd from $SRC$SPATH"
echo "  CONF_ARCH= $CONF_ARCH"

ln -fs $SRC$SPATH/.purpose .

file="config.h"
dest=$file.tmp

echo "#ifndef __config_h__" > $dest
echo "#define __config_h__" >> $dest
echo "#define CONF_DATE \""$CONF_DATE"\"" >> $dest
echo "#define CONF_SYS \""$CONF_SYS"\"" >> $dest
echo "#define CONF_HOST \""$CONF_HOST"\"" >> $dest
echo "#define CONF_USER \""$CONF_USER"\"" >> $dest
echo "#define CONF_ARCH \""$archtypes"\"" >> $dest
for arch in $archtypes ; do
	if [ $arch != "." ] ; then
		echo "#define ARCH_"$arch >> $dest
	fi
done
echo "#endif" >> $dest

if [ -f $file ] ; then
	tail +4 $file > $file.1
fi
tail +4 $dest > $file.2
if cmp -s $file.1 $file.2 ; then
	echo "$file: -- no changes --"
else
	cp $dest $file
fi
rm -f $dest $file.1 $file.2


rm -f config.log
mk="Makefile"
cv="config.var"
fconfig=$BASE/bin/fconfig

echo "Makefile: $SRC/Makefile.head" > $mk
cat $SRC/Makefile.head >> $mk
if [ -f $fconfig ] ; then
	$fconfig "$archtypes" "$SRC" $SPATH $cv
else
	echo "SRC=$SRC" > $cv
	echo "SPATH=$SPATH" >> $cv
	echo "BASE=$BASE" >> $cv
fi
echo "Makefile: $cv" >> $mk
cat $cv >> $mk
if [ -f $fconfig ] ; then
	$fconfig "$archtypes" "$SRC" $SPATH -m $mk Make
else
	echo "Makefile: $SRC$SPATH/Make" >> $mk
	cat $SRC$SPATH/Make >> $mk
fi
echo "Makefile: $SRC/Makefile.tail" >> $mk
cat $SRC/Makefile.tail >> $mk

exit 0

