#!/usr/bin/env bash
# Generate the HTML/PDF export(s) from any .adoc document (README.adoc by default).
#
#   docs/generate-readme-pdf.sh                     # README.html + README.pdf
#   docs/generate-readme-pdf.sh --html              # README.html only
#   docs/generate-readme-pdf.sh --pdf               # README.pdf only
#   docs/generate-readme-pdf.sh DEPLOY.adoc         # DEPLOY.html + DEPLOY.pdf
#   docs/generate-readme-pdf.sh DEPLOY.adoc --pdf   # DEPLOY.pdf only
#
# Outputs land in the project root (named after the source) and are Git-ignored.
#
# Requirements:
#   - asciidoctor            (e.g. gem install asciidoctor)
#   - chromium               (headless PDF rendering)
#   - fonts-noto-color-emoji (color emoji in the PDF)
#
# Why Chromium instead of asciidoctor-pdf (used by the VSCodium extension)?
# Its Prawn engine cannot embed color-emoji fonts (CBDT/COLR), so emoji
# disappear. Chromium handles them fine as long as "Noto Color Emoji"
# is installed. The docs/docinfo.html stylesheet (emoji fallback + print
# rules) is injected only for this build, via Asciidoctor's docinfo
# mechanism, and adapts the layout for print (TOC in flow, table/page
# breaks, wrapped code listings).

set -euo pipefail

cd "$(dirname "$0")/.." || exit 1

SRC="README.adoc"
MODE="--all"

for arg in "$@"; do
    case "$arg" in
        --html|--pdf|--all)
            MODE="$arg"
            ;;
        -h|--help)
            sed -n '2,12p' "$0"
            exit 0
            ;;
        *.adoc)
            SRC="$arg"
            ;;
        *)
            echo "Usage: $0 [fichier.adoc] [--html|--pdf|--all]" >&2
            exit 1
            ;;
    esac
done

if [[ ! -f "$SRC" ]]; then
    echo "Erreur : fichier introuvable : $SRC" >&2
    exit 1
fi

BASE="$(basename "$SRC" .adoc)"
HTML_OUT="$BASE.html"
PDF_OUT="$BASE.pdf"

build_html() {
    asciidoctor -b html5 -a docinfodir=docs -a docinfo=shared "$SRC" -o "$1"
    echo "HTML generated: $1"
}

build_pdf() {
    # Resolve to an absolute path for the file:// URL
    local html_path="$1"
    [[ "$html_path" != /* ]] && html_path="$PWD/$html_path"
    chromium --headless --disable-gpu --no-sandbox \
        --no-pdf-header-footer \
        --print-to-pdf="$PDF_OUT" \
        "file://$html_path"
    echo "PDF generated: $PDF_OUT"
}

case "$MODE" in
    --html)
        build_html "$HTML_OUT"
        ;;
    --pdf)
        TMP_HTML="$(mktemp --suffix=.html)"
        trap 'rm -f "$TMP_HTML"' EXIT
        build_html "$TMP_HTML" >/dev/null
        build_pdf "$TMP_HTML"
        ;;
    --all)
        build_html "$HTML_OUT"
        build_pdf "$HTML_OUT"
        ;;
esac
