#!/bin/sh
set -e

PATH=/usr/lib/debiandoc-sgml/bin:$PATH
export PATH

[ "$DEBIANDOCSGMLLIB" ] || DEBIANDOCSGMLLIB=/usr/lib/debiandoc-sgml/sgml
[ "$DEBIANDOCSGMLSPEC" ] || DEBIANDOCSGMLSPEC=/usr/lib/debiandoc-sgml/spec

usageversion () {
	cat >&2 <<'END'
debiandoc2latex2e version 0.2; Copyright (C)1997 Christian Leutloff.
Based on debiandoc2lout version 1.0; Copyright (C)1996 Ian Jackson.
This is free software; see the GNU General Public Licence
version 2 or later for copying conditions.  There is NO warranty.

usage: debiandoc2latex2e [options] <filename>.sgml
options:  -k      keep intermediate files
          -O      send output to stdout instead of <filename>.tex
END
}

usageerror () { echo >&2 "debiandoc2latex2e: $@"; usageversion; exit 2; }

keep=false
stdout=false

while [ $# != 0 ]
do
	case "$1" in
	-k)	keep=true	;;
	-O)	stdout=true	;;
	-?*)	usageerror "unknown option \`$1'" ;;
	--)	shift; break	;;
	*)	break		;;
	esac
	shift
done

[ $# = 1 ] || usageerror "need exactly one input filename"

case "$1" in
-)	nsgmlsi="-"
	stdout=true
	$stdout || usageerror "stdin not allowed with debiandoc2latex2e"
	! $keep || usageerror "-k not allowed with input from stdin"
	;;
-?*)	nsgmlsi="./$1"
	bn="`basename \"$1\" .sgml`"
	;;
*)	nsgmlsi="$1"
	bn="`basename \"$1\" .sgml`"
	;;
esac

case "$bn" in -*) bn="./$bn" ;; esac

rc=2
if $keep
then
	tf="$bn"
else
	tfd=/tmp/$$
	trap 'rm -rf $tfd; exit $rc' 0
	mkdir "$tfd"
	tf="$tfd/y"
fi

nsgmls -l -D"$DEBIANDOCSGMLLIB" -ccatalog "$nsgmlsi" >"$tf.sasp"
saspconvert opt . <"$tf.sasp" >"$tf.sasp-latex2e"
$stdout || exec >"$bn.tex"
sgmlspl "$DEBIANDOCSGMLSPEC"/latex2e <"$tf.sasp-latex2e" ""

rc=0
