#!/bin/sh
#
# source sgml files directory
SGML_DIR='./doc/xorg-docs/sgml'
# processed files destination directory
DOCBOOK_DIR='./doc/xorg-docs/docbook-xml'

# check if the script is running from the correct location
if ! [ -e $SGML_DIR ]
then
    echo
    echo "Launch this script from the root of the modular tree."
    echo "The expected relative path to the sgml directory is: $SGML_DIR"
    echo
    exit 1
fi    

# make destination directory
mkdir $DOCBOOK_DIR

for sgml_file in $SGML_DIR/*.sgml
do 
    basename=$(basename $sgml_file)
    output_file=$(basename $sgml_file .sgml).xml

    echo "### Processing: $basename"

    if [ $basename != "XACE-Spec.sgml" ]
    then
        # cut everything before the opening <article> tag
            perl -we '$found=0; while(<>) {if (/<article>/i) {$found=1}; print if $found}' $sgml_file |\
        # re-insert old doctype declaration, but without entity declarations
            sed '1i <!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook V4.2//EN" >' |\
        # hide entity references from the parsers: '&nbsp;' becomes '|||nbsp;'
            sed 's/\&/|||/g' |\
        # comment-out conditional sections delimiters
            sed -e 's/<!\[.*%.*\[/<!--BEGIN & END-->/g' -e 's/\]\]>/<!--BEGIN & END-->/g' |\
        # convert tags to lower case, check closing tags, remove doctype declaration etc.
            sgml2xml -x lower -x cdata -x comment |\
        # append new doctype declaration; comment-out the entity reference
            sed '1a <!DOCTYPE article PUBLIC "-//OASIS//DTD Docbook XML V4.4//EN" "http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd"' |\
            sed '2a [<!--' |\
            sed '3a <!ENTITY % defs SYSTEM "X11/defs.ent"> %defs;' |\
            sed '4a -->]>' |\
        # make the markup more human-readable
            tidy -q -i -wrap 79 -xml |\
        # unhide the entity declaration
            sed -e '4 s/<!--//' -e '6 s/-->//' |\
        # uncomment the conditional sections
            sed -e 's/<!--BEGIN //' -e 's/ END-->//' |\
        # unhide entity references ('|||nbsp;' returns '&nbsp;') and write down
        # new docbook-xml file
            sed 's/|||/\&/g' > "$DOCBOOK_DIR/$output_file";
    else
        # treat XACE-Spec.sgml as a special case, since it already is in xml format
        cp $sgml_file "$DOCBOOK_DIR/$output_file";
    fi    
done
