#!/bin/sh

# Copyright © 2014-2019 Jakub Wilk <jwilk@jwilk.net>
#
# This file is part of pdf2djvu.
#
# pdf2djvu is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# pdf2djvu is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.

set -e -u

usage()
{
    printf 'Usage: %s [-l] <src> <dst>\n' "$0"
}

here=$(dirname "$0")
opt_lang=
while getopts 'hl' opt
do
    case "$opt" in
        l) opt_lang=y;;
        h) usage; exit 0;;
        *) usage >&2; exit 1;;
    esac
done
shift $((OPTIND - 1))
[ $# -eq 2 ] || { usage; exit 1; }
src="$1"
dst="$2"
xsl="$here/manpage.xsl"
xmllint='xmllint --valid --noout --nonet'
xsltproc='xsltproc --nonet'
[ -n "$opt_lang" ] && xsltproc="$xsltproc --param man.output.lang.in.name.enabled 1"
PS4='$ '
set -x
$xmllint "$src"
$xsltproc "$xsl" "$src"
perl -pi -e '
if (/^[.]SH /) {
    # work-arounds for DocBook XSL capitalization bugs
    s/(\\[(][,~\x27][a-z])/\U$1/g; # https://bugs.debian.org/758262#20
    s/\\[(]ss/SS/g; # https://bugs.debian.org/773444
}
'"# prefer ' to \(aq when used as an apostrophe"'
s/([a-z])\\[*][(]Aq([a-z])/$1\x27$2/gi
' "$dst"

# vim:ts=4 sts=4 sw=4 et
