#! /bin/bash

# We could have multiple occurances.  Create all of them.
FILE=$1

TMPF=`mktemp /tmp/gen-help.XXXXXX`
trap "rm -f $TMPF*" EXIT
cmdsed='s,.*<command>[ 	]*\([^ 	]*\)[ 	]*</command>.*,\1,p'

STARTLINE=1
for LINE in `fgrep -n '/*** XML Help:' < $FILE | cut -d: -f1`; do
    if [ -L tools/link-dtd ]; then
	echo '<?xml version="1.0"?>' > $TMPF
	echo '<!DOCTYPE article PUBLIC "-//OASIS//DTD Docbook XML V4.1.2//EN"' \
	    >> $TMPF
	echo '"'`pwd`'/tools/link-dtd/docbookx.dtd">' >> $TMPF
	echo '<article><section>' >> $TMPF
	tools/extract-help $FILE $LINE >> $TMPF
	echo '</section></article>' >> $TMPF

	tr '\n' ' ' < $TMPF | sed -e 's/[[:space:]]\{2,\}/ /g' |
        xsltproc tools/text.xsl - | fold -w80 -s > $TMPF.txt

	COMMAND=`sed -n "$cmdsed" < $TMPF | head -n +1`
	COMMAND_FILE=generated-`basename $FILE .c`-help:$COMMAND
	#echo Creating $COMMAND_FILE

        # Output description, in quotes.
	echo 'log_line(LOG_ALWAYS,' > $COMMAND_FILE

	TXTSTART=`grep -n '^  1\.1\.' $TMPF.txt | cut -d: -f1`
	tail -n +`expr $TXTSTART + 2` $TMPF.txt | while read -r TXTLINE; do
	    echo "$TXTLINE" | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' -e 's/^/"/' \
		-e 's/$/\\n"/' >> $COMMAND_FILE
	done
	echo ');' >> $COMMAND_FILE
    else
	tools/extract-help $FILE $LINE > $TMPF

	COMMAND=`sed -n "$cmdsed" < $TMPF | head -n +1`
	COMMAND_FILE=generated-`basename $FILE .c`-help:$COMMAND
	echo Faking up $COMMAND_FILE

	echo 'log_line(LOG_ALWAYS,' > $COMMAND_FILE
	sed 's/<arg [^>]*>/   /;s/<[^>]*>//g' < $TMPF |
	    sed -e 's/\\/\\\\/g' -e 's/"/\\"/g' -e 's/^/"/' -e 's/$/\\n"/' \
		>> $COMMAND_FILE
	echo ');' >> $COMMAND_FILE
    fi

    STARTLINE=$LINE
done
