#!/bin/sh
# QA helper. render.sh <passport.html> [dark]
# Prints the passport to <name>.pdf and screenshots its first visa page (#p1) at
# 397 by 559 pixels to <name>.png with headless Chromium, then prints the PDF's
# page count as a bare integer. The colour-scheme preference is always set
# explicitly (Chromium: 0 is dark, 1 is light); with `dark` the outputs are
# <name>-dark.pdf and <name>-dark.png.
set -eu
html=$1
scheme=1
suffix=
if [ "${2:-}" = dark ]; then scheme=0; suffix=-dark; fi

chrome=${CHROME:-}
if [ -z "$chrome" ]; then
  for name in chromium chromium-browser google-chrome; do
    if command -v "$name" >/dev/null 2>&1; then chrome=$(command -v "$name"); break; fi
  done
fi
[ -n "$chrome" ] || chrome="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"

dir=$(cd "$(dirname "$html")" && pwd)
file=$(basename "$html")
base=$dir/${file%.html}$suffix
profile=$(mktemp -d)
trap 'rm -rf "$profile"' EXIT

run() {
  "$chrome" --headless --disable-gpu --hide-scrollbars --user-data-dir="$profile" \
    --blink-settings=preferredColorScheme=$scheme "$@" </dev/null >/dev/null 2>&1
}
rm -f "$base.pdf" "$base.png"
run --no-pdf-header-footer --print-to-pdf="$base.pdf" "file://$dir/$file"
run --window-size=397,559 --screenshot="$base.png" "file://$dir/$file#p1"
grep -aoE '/Type /Page([^s]|$)' "$base.pdf" | wc -l | tr -d ' '
