#!/bin/sh
#
# mkpages.sh - For each category passed on the command line, make a
#		HTML pages listing the records in that category.
#
#	syntax: mkpages QDDBDIR RELATION KEYFIELD NAMEFIELD ANCHORFIELD \
#			URLFIELD category1 <category2 ... categoryN>
#
#	To invoke this for ALL categories, use:
#	cd targetdir;
#	mkpages QDDBDIR RELATION KEYFIELD NAMEFIELD ANCHORFIELD URLFIELD \
#		`categories QDDBDIR RELATION KEYFIELD | tr '\n' ' '`
#
#	NOTE it ASSUMES itself to be located in the target directory
#	and the relation directory to be found in the QDDBDIR directory.
#

ISPUTIL="/var/lib/ISPutil"
ISPDBS="/var/lib/ISPutil/qdDBs"
WWWUTIL="/var/lib/WWWutil"
PAGEMAKE=$WWWUTIL/pagemake
WWWDBS="/var/lib/WWWutil/qdDBs"
WWWDB=$WWWDBS/WWWutil

if [ "$CGIBIN" = "" ]; then
  CGIBIN=/cgi-bin
fi

QBIN="/usr/local/qddb/bin"
QUERY=$QBIN/query
AWK="/usr/bin/awk"


if [ "$WWWPROJECT" = "" ]; then
  WWWPROJECT=WWWutil
fi


QDDBDIR=$1 ; shift
RELATION=$1 ; shift
KEYFIELD=$1; shift
NAMEFIELD=$1; shift
ANCHORFIELD=$1; shift
URLFIELD=$1; shift

tmpfile=/tmp/mkpages.$$

if [ "$NAMEFIELD" = "Company.Contact.Username" \
	-a "$QDDBDIR" = "$ISPDBS" -a "$RELATION" = "Clients" ]; then
  CGI="$CGIBIN/userinfo"
  AWKFILE=$PAGEMAKE/mkupage.awk
else
  CGI="${CGIBIN}/${RELATION}info"
  AWKFILE=$PAGEMAKE/mkpage.awk
fi

#HEADPRINTF="`$QUERY $WWWDB -sep ' ' Name $WWWPROJECT -print Header`"
#FOOTPRINTF="`$QUERY $WWWDB -sep ' ' Name $WWWPROJECT -print Footer`"

HEADPRINTF=`cat header.printf`

# Loop while there are categories left to do
while [ ! -z $1 ]; do

category="$1"
shift
targetfile=$category.spider


# header from WWWutil DB  is a printf format string for printing two strings:
#	(the two strings being the Title and the H1 header)

printf "$HEADPRINTF" "$RELATION: $category" "$RELATION: $category" >$tmpfile

echo "<BR CLEAR=ALL>" >> $tmpfile
echo "<TABLE>" >> $tmpfile

# Query the database for all records in this category
$QUERY $QDDBDIR/$RELATION -sep "::" $KEYFIELD $category \
	-print $NAMEFIELD $ANCHORFIELD $URLFIELD | sort -bdfi \
	| $AWK -f $AWKFILE -v cgi="$CGI" \
		-v category=$category \
	>>$tmpfile

echo "</TABLE><P><P>" >> $tmpfile

cat footer.printf >> $tmpfile


cp -- $tmpfile $targetfile
rm -f $tmpfile

# end of categories-loop
done
