#!/bin/sh
set -e

usageversion () {
	echo >&2 \
'debiandoc2ps version 1.1

Copyright (C) 1998 Ardo van Rangelrooij
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: debiandoc2ps [options] <filename>.sgml
options:  -k              keep intermediate files
          -p<papersize>   generate output for named paper size
          -O              send output to stdout instead of <filename>.ps
          -1              do not do 2-up printing'
}

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

nup=true
stdout=false
keep=false
keepopt=''

while [ $# != 0 ]
do
	case "$1" in
	-k)	keep=true;
		keepopt="-k"
		;;
	-O)	stdout=true
		;;
	-1)	nup=false
		;;
	-p*)	PAPERCONF="`echo \"x$1\" | sed -e 's/^x-p//'`";
		export PAPERCONF ;;
	-?*)	usageerror "unknown option \`$1'"
		;;
	--)	shift;
		break
		;;
	*)	break
		;;
	esac
	shift
done

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

case "$1" in
-)	louti="-"
	stdout=true
	if $keep; then usageerror "-k not allowed with input from stdin"; fi
	;;
-?*)	louti="./$1"
	bn="`basename \"$1\" .sgml`"
	;;
*)	louti="$1"
	bn="`basename \"$1\" .sgml`"
	;;
esac

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

tf1="$bn.lout"
tf2="$bn.ps1"
tf3="$bn.ps1x"

debiandoc2lout $keepopt -O "$louti" >"$tf1"

if command -v lout >/dev/null 2>&1;
then
    (
	if $nup
	then
		exec >"$tf2"
	else
		$stdout || exec >"$bn.ps"
	fi
	set +e
	lout "$tf1" >/dev/null 2>&1
	lout "$tf1" >/dev/null 2>&1
	set -e
	lout "$tf1"
    )
else
    usageerror "lout not found"
fi

if ! $nup; then exit 0; fi

if ! command -v psnup >/dev/null 2>&1;
then
    usageerror "psnup not found"
fi

if ! command -v paperconf >/dev/null 2>&1;
then
    usageerror "paperconf not found"
fi

perl -e '
	while (<>) {
		if (m/^\%\%Page: /) {
			print(<<END) || die $!;
%%Page: 0 0
%%BeginPageSetup
%%PageResources:
%%EndPageSetup
END
			last;
		}
		print || die $!;
	}
	do { print || die $!; } while (<>);
	close(STDOUT) || die $!;
' <"$tf2" >"$tf3"

$stdout || exec >"$bn.ps"

psnup -p"`paperconf -n`" -2 <"$tf3"

if ! $keep
then
    rm -f $tf1 $tf1.ld $tf2 $tf3 lout.li
fi
