#!/bin/zsh
# Check an issue before it prints: the auto fit report, empty space in every column, cell and box on every page
# (gapcheck.js, fails anything over 5%), page overflow, then print the PDF and render every page as a PNG to look at.
# Usage: check.sh issues/YYYY-MM-DD/bella-bulletin-YYYY-MM-DD.html [out folder, default the issue's check/ folder]
[ -n "$1" ] || { echo "usage: check.sh <issue html> [out folder]"; exit 1; }
F="${1:A}"; [ -f "$F" ] || { echo "no such file: $F"; exit 1; }
HERE="${0:A:h}"; DIR="${F:h}"; OUT="${2:-$DIR/check}"; OUT="${OUT:A}"; mkdir -p "$OUT"
CHROME="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
T=$(mktemp -d -t bella-check)

# 1. a throwaway copy with the empty space checker added (the issue file itself is never touched)
python3 - "$F" "$HERE/gapcheck.js" "$T/page.html" <<'PY'
import sys,pathlib
src,js,dst=sys.argv[1:]; s=open(src).read(); d=pathlib.Path(src).parent.as_uri()+'/'
s=s.replace('<head>','<head><base href="'+d+'">',1)
i=s.rfind('</body>'); s=s[:i]+'<script>'+open(js).read()+'</script>'+s[i:]
open(dst,'w').write(s)
PY

# 2. dump the laid out page and read both reports
"$CHROME" --headless=new --disable-gpu --allow-file-access-from-files --window-size=794,1123 --virtual-time-budget=10000 --dump-dom "file://$T/page.html" > $T/dom.html 2>/dev/null &
CP=$!; for i in $(seq 1 60); do [ -s $T/dom.html ] && grep -q '</html>' $T/dom.html && break; sleep 1; done; sleep 1; kill $CP 2>/dev/null

# 3. print the PDF and render each page as a PNG
PDF="$OUT/${F:t:r}.pdf"
"$CHROME" --headless=new --disable-gpu --allow-file-access-from-files --no-pdf-header-footer --virtual-time-budget=10000 --print-to-pdf="$PDF" "file://$F" >/dev/null 2>&1
python3 - "$PDF" "$OUT" <<'PY'
import sys,fitz
d=fitz.open(sys.argv[1])
for i,p in enumerate(d): p.get_pixmap(dpi=110).save(f"{sys.argv[2]}/page-{i+1}.png")
print(f"PDF: {sys.argv[1]} ({len(d)} pages); PNGs: {sys.argv[2]}/page-1..{len(d)}.png")
PY

python3 "$HERE/checkreport.py" $T/dom.html "$PDF"
R=$?; rm -rf $T; exit $R
