#!/bin/sh
# Linux native writer regression only; does not certify the application cohort.
set -eu
ulimit -c 0
cd "$(dirname "$0")/.."
T=$(mktemp -d /tmp/signet-image-memory.XXXXXX)
trap 'rm -rf "$T"' 0
trap 'exit 1' HUP INT TERM
CC=${CC:-cc}
"$CC" -O2 -std=c99 -Wall -Wextra test/resource-image.c -lpng -o "$T/image"
"$CC" -O2 -std=c99 -Ivendor -c vendor/sha256.c -o "$T/sha256.o"
"$CC" -O2 -std=c99 -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=700 -Wall -Wextra \
    -Isrc -Ivendor test/resource-pdfw.c src/pdfw.c src/ttf.c src/util.c \
    "$T/sha256.o" -lpng -lz -lm -o "$T/writer"
"$T/image" "$T/image.png" "$T/rgb"
cp /usr/share/fonts/dejavu/DejaVuSans.ttf "$T/font.ttf"
dd if=/dev/zero bs=1048576 count=2 >> "$T/font.ttf" 2>/dev/null
"$T/writer" "$T/font.ttf" "$T/image.png" "$T/image.pdf"
if "$T/writer" "$T/font.ttf" "$T/image.png" /dev/full; then
    echo 'FAIL - writer accepted a failed output stream' >&2
    exit 1
fi
qpdf --check "$T/image.pdf" > /dev/null
qpdf --json "$T/image.pdf" > "$T/image.json"
font_bytes=$(wc -c < "$T/font.ttf")
image_obj=$(jq -er '.qpdf[1] | to_entries | map(select(.value.stream.dict["/Subtype"] == "/Image")) | if length == 1 then .[0].key | capture("obj:(?<id>[0-9]+)").id else error("expected one image") end' "$T/image.json")
font_obj=$(jq -er --argjson size "$font_bytes" '.qpdf[1] | to_entries | map(select(.value.stream.dict["/Length1"] == $size)) | if length == 1 then .[0].key | capture("obj:(?<id>[0-9]+)").id else error("expected exact font") end' "$T/image.json")
qpdf --show-object="$image_obj" --filtered-stream-data "$T/image.pdf" > "$T/actual-rgb"
qpdf --show-object="$font_obj" --filtered-stream-data "$T/image.pdf" > "$T/actual-font"
cmp "$T/rgb" "$T/actual-rgb"
cmp "$T/font.ttf" "$T/actual-font"
pdftotext "$T/image.pdf" "$T/text"
grep -q 'Font stays live while PNG is embedded: ₹' "$T/text"
echo 'image memory contract: maximum PNG and live font, exact RGB/font bytes and Unicode passed'
