#!/usr/bin/env bash
# man2htmldoc --- convert a project groff man page to a styled standalone
# HTML page matching the look of the Org-exported documentation
# (same body font/width and link colour as Index.org).
#
# Usage:  man2htmldoc SRC.1 DEST.html
#
# This is NOT the man2html(1) from the man2html-base package: that tool is
# a CGI helper --- it emits an HTTP "Content-type:" header line and a
# hardcoded "Return to Main Contents" link to /cgi-bin/man/man2html, with
# no option to suppress either or to inject our styling and our index
# back-link. We need a clean static page wired into the documentation set,
# so we keep this small converter under a distinct name to avoid any PATH
# clash with the packaged tool.
#
# Depends only on groff (mandoc macros) and awk --- both universally
# available wherever the rest of the toolchain runs. No external CSS or
# network resource: the page is self-contained so it survives being moved
# into the distribution archive alongside the other *.html files.

set -eu

src="$1"
dest="$2"

if ! command -v groff >/dev/null 2>&1; then
    echo "man2htmldoc: groff not found; cannot convert $src" >&2
    exit 1
fi

# groff -Thtml emits a complete <html> document with its own <style>.
# We append our stylesheet and an index back-link just before </head>,
# so our rules win by cascade order. awk does the injection portably.
groff -mandoc -Thtml "$src" | awk '
/<\/head>/ {
    print "<style>"
    print "  body { font-family: sans-serif; max-width: 760px; margin: 2em auto; }"
    print "  h1   { border-bottom: 2px solid #444; padding-bottom: 0.3em; }"
    print "  h2   { margin-top: 1.5em; color: #222; }"
    print "  a    { color: #0055aa; }"
    print "  pre, code { font-family: monospace; }"
    print "  hr   { display: none; }"
    print "</style>"
    print "</head>"
    next
}
/<body>/ {
    print
    print "<p style=\"max-width:760px;margin:0.5em auto;font-size:90%;\"><a href=\"../Index.html\">&larr; Documentation index</a></p>"
    next
}
{ print }
'  > "$dest"

echo "man2htmldoc: wrote $dest"
