#! /bin/sh

# $Progeny$

set -e

progname=man-wrapper.sh
doctools=$(dirname $0)
basedir=${doctools}/..

# default output mode is SGML
mode=sgml

# display a usage message
usage () {
    cat << EOF
Usage: $progname [OPTION ...] document

generates wrapper for SGML- or XML-formatted manual page document

Options:
-h  --help  display this usage message and exit
-s  --sgml  generate SGML wrapper
-x  --xml   generate XML wrapper
EOF
    :;
}

# parse command line
args=$(getopt --options +hsx \
       --long help,sgml,xml \
       --name "$progname" -- "$@")

eval set -- "$args"

while :; do
    case "$1" in
        -h|--help) showhelp=1 ;;
        -s|--sgml) mode=sgml ;;
        -x|--xml) mode=xml ;;
        --) shift; break ;;
        *) echo "$progname: error while parsing option \"$1\"" >&2; USAGE=$(usage); echo "$USAGE" >&2; exit 1 ;;
    esac
    shift
done

if [ "$showhelp" ]; then
    usage
    exit 0
fi

refentry=$1

if [ "$mode" = "sgml" ]; then
    doctype_line='<!doctype refentry PUBLIC "-//OASIS//DTD DocBook V4.1//EN"'
elif [ "$mode" = "xml" ]; then
    doctype_line='<?xml version="1.0" standalone="no"?>
<!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBk XML V4.1.2//EN"
        "/usr/share/sgml/docbook/dtd/xml/4.1.2/docbookx.dtd"'
else
    echo "$progname: error!  Unrecognized mode \"$mode\"; choking and dying." >&2
fi

cat << EOF
$doctype_line
[
EOF

# XXX: the next three if blocks scream for a stupid eval trick

if [ -f ${doctools}/progeny.ent ]; then
    cat << EOF
<!ENTITY % progeny-entity SYSTEM "${doctools}/progeny.ent">
%progeny-entity;
EOF
fi

if [ -f ${doctools}/config.ent ]; then
    cat << EOF
<!ENTITY % config-entity SYSTEM "${doctools}/config.ent">
%config-entity;
EOF
fi

if [ -f ${basedir}/package.ent ]; then
    cat << EOF
<!ENTITY % package-entity SYSTEM "${basedir}/package.ent">
%package-entity;
EOF
fi

cat << EOF
<!ENTITY myrefentry SYSTEM "${refentry}">
]>
EOF

cat << EOF
<refentry>
&myrefentry;
</refentry>
EOF

# vim:set ai et sts=4 sw=4 tw=0:
