#!/bin/sh -
# Process system description files into the include/libsupport.h file and
# into sed command that are applies to makefiles to use appropriate include
# directories and libraries.
#
# This command should be invoked from the toplevel zmailer directory with
# the name of the Config file and the file containing module dependencies
# as argument.  This is most conveniently done from within the toplevel
# Makefile.
#
case $# in
3)	;;
*)	echo "Usage:$#: $0 SiteConfig Config Dependencies < hostenv/file"
	exit 1
	;;
esac
if [ ! -s $2.sed ]; then
	echo "Usage: $0 SiteConfig Config Dependencies < hostenv/file"
	exit 1
fi

TMP=features$$
trap "rm -f $TMP" 0 1 2 3 15
echo > $TMP
sed -n  -e '/^[^# 	]*=[ 	]*/!d' \
	-e 's:^\([^ 	]*\)=[ 	]*\([^#].*\):\1=\2:' \
	-e 's:=\([^# 	]*[ 	][^#]*\)\(.*\):="\1"\2:' \
	-e 's:\([ 	][ 	]*\)":"\1:' -e 's:""::' \
	-e "/_LIB=/w $TMP" -e "/_INCL=/w $TMP" -e "/^LIB_TSORT=/w $TMP" \
	-e 's:^\(.*\)=:#define	\1	:' \
	-e '/^[^_]*_LIB/!{ /^[^_]*_INCL/!{ /LIB_TSORT/!{ /_/p
}
}
}' \
	-e 's:\(#define.\)\([^_ 	][^_ 	]*\)_.*:\1USE_\2:p' \
	-e 's:\(#define.\)\([^_][^_]*\)$:\1USE_\2:p' |
sort -u > include/libsupport.h

. ./$TMP
cat $3 | sed -e 's/#.*//' | tr '[a-z]' '[A-Z]' |
while read module requirements
do
	for req in $requirements
	do
		eval echo ${module}_INCL -I"\${${req}_INCL}"
		eval echo ${module}_LIB "\${${req}_LIB}"
	done
done |
awk '{
  if (NF > 1) {
	for (i = 2; i <= NF ; ++i) {
		j = index("'"$LIB_TSORT"'", $i)
		print j " " $1 " " $i
	}
  } else
	print 0 " " $0
}' | sort +1 -2 +0n | uniq |
awk '
NF>2 {	if ( $3 != "-I" ) {
		foo[$2] = foo[$2] " " $3;
	} else
		foo[$2] = foo[$2] ""
}
NF==2 { foo[$2] = "" }
END   { for (i in foo) {
		print "s~^" i "=.*~" i "=	" foo[i] "~";
	}
}' >> $2.sed
