#!/bin/sh
# report-pdf.sh -- turn a Markdown page into a PDF with tools/report.css.
#
# Usage:
#   tools/report-pdf.sh FILE.md [OUT.pdf]      (OUT defaults to FILE.pdf)
#
# Writes OUT.pdf, and OUT.html beside it: one self-contained file (styles and
# logo inside) that opens in any browser, for sharing or a wiki.
#
# Markdown -> HTML (pandoc) -> PDF (weasyprint), styled by report.css: A4
# landscape for wide tables, a small font, header rows repeated on each page,
# page numbers. Made for elm-compare-portals.sh's page, but any Markdown works:
#
#   tools/elm-compare-portals.sh prod,preprod,test critical.txt > differences.md
#   tools/report-pdf.sh differences.md
#
# LOGO=/path/to/logo.png (or .svg, .jpg) puts that image in the top-right
# corner of every page, e.g. your company's logo. Keep it outside the repo.
#
# Needs pandoc and weasyprint (macOS: brew install pandoc weasyprint). Without
# weasyprint it still writes the HTML: open that in a browser and print it to
# PDF, which applies the same styles (without the Summary's page numbers).

set -eu
md=${1:?usage: $0 FILE.md [OUT.pdf]}
pdf=${2:-${md%.md}.pdf}
html=${pdf%.pdf}.html
css="$(dirname "$0")/report.css"

command -v pandoc >/dev/null || { echo "report-pdf: pandoc not found (brew install pandoc)" >&2; exit 1; }

# the page's first heading names the document (pagetitle sets <title> only, so
# it is not printed a second time)
title=$(sed -n 's/^# //p' "$md" | head -1)

# the logo goes in at the top of the page; report.css moves it into each page's
# top-right corner, and --embed-resources copies the image into the HTML
before=/dev/null
if [ -n "${LOGO:-}" ]; then
    [ -r "$LOGO" ] || { echo "report-pdf: cannot read LOGO $LOGO" >&2; exit 1; }
    logo=$(cd "$(dirname "$LOGO")" && pwd)/$(basename "$LOGO")
    before=$(mktemp)
    trap 'rm -f "$before"' EXIT
    printf '<div class="report-logo"><img src="%s" alt=""></div>\n' "$logo" > "$before"
fi
pandoc "$md" -s --embed-resources -c "$css" --metadata pagetitle="${title:-Report}" \
    --include-before-body "$before" -o "$html"

if command -v weasyprint >/dev/null; then
    # weasyprint warns about pandoc's screen-only styles and font subsetting; not useful here
    weasyprint "$html" "$pdf" 2>/dev/null
    echo "$pdf" >&2
    echo "$html" >&2
else
    echo "report-pdf: weasyprint not found (brew install weasyprint); wrote $html -- open it in a browser and print to PDF" >&2
    exit 1
fi
