#!/bin/bash
# Build the one page Bella Times test PDF from cover.html, then shrink the photo so it emails to the Brother printer.
# Usage: ./build.sh    Needs: Google Chrome or Chromium, python3 with PyMuPDF (pip3 install pymupdf).
# Output: pdf/bella-times-test-2026-10-26.pdf
set -euo pipefail
cd "$(dirname "$0")"
OUT=pdf/bella-times-test-2026-10-26.pdf; mkdir -p pdf
CHROME=""
for c in "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" google-chrome google-chrome-stable chromium chromium-browser; do
  if command -v "$c" >/dev/null 2>&1 || [ -x "$c" ]; then CHROME="$c"; break; fi
done
[ -n "$CHROME" ] || { echo "Chrome or Chromium not found"; exit 1; }
"$CHROME" --headless=new --disable-gpu --no-sandbox --allow-file-access-from-files --no-pdf-header-footer \
  --virtual-time-budget=10000 --print-to-pdf="pdf/print.pdf" "file://$PWD/cover.html" >/dev/null 2>&1
python3 - pdf/print.pdf "$OUT" <<'PY'
import sys, os, fitz
src, out = sys.argv[1:]; d = fitz.open(src)
for page in d:
    for im in page.get_images(full=True):
        x, smask = im[0], im[1]
        if len(d.xref_stream_raw(x)) < 150_000: continue
        if smask:
            a = fitz.Pixmap(d, smask).samples
            if sum(1 for v in a[::5] if v < 250) / len(a[::5]) > 0.10: continue  # see through (the kiss): leave it
        pix = fitz.Pixmap(d, x)
        if pix.alpha: pix = fitz.Pixmap(pix, 0)
        if pix.colorspace.n != 3: pix = fitz.Pixmap(fitz.csRGB, pix)
        d.update_stream(x, pix.tobytes('jpeg', jpg_quality=80), compress=False)
        d.xref_set_key(x, 'Filter', '/DCTDecode'); d.xref_set_key(x, 'ColorSpace', '/DeviceRGB')
        d.xref_set_key(x, 'BitsPerComponent', '8'); d.xref_set_key(x, 'DecodeParms', 'null')
d.save(out, garbage=4, deflate=True)
print(f"{out}: {os.path.getsize(out)/1e6:.1f} MB, {len(fitz.open(out))} page")
PY
rm -f pdf/print.pdf
shasum -a 256 "$OUT"
