#!/bin/sh
# Native image writer regression; source/fixtures are synthetic, services unused.
set -eu
ulimit -c 0
cd "$(dirname "$0")/.."
TMP=$(mktemp -d /tmp/signet-image.XXXXXX)
trap 'rm -rf "$TMP"' EXIT
${CC:-cc} -O2 -std=c99 -Ivendor -c vendor/sha256.c -o "$TMP/sha256.o"
${CC:-cc} -O2 -std=c99 -D_DEFAULT_SOURCE -D_XOPEN_SOURCE=700 -Wall -Wextra \
    -Isrc -Ivendor test/image-contract.c src/pdfw.c src/ttf.c src/util.c \
    "$TMP/sha256.o" -lpng -lz -lm -o "$TMP/image-contract"
"$TMP/image-contract" test/fixtures/image.jpg test/fixtures/seal.png "$TMP"
qpdf --check "$TMP/image.pdf" >/dev/null
qpdf --json "$TMP/image.pdf" > "$TMP/image.json"
jq -e '[.. | objects | select(.["/Subtype"]? == "/Image") | .["/Interpolate"]] | length > 0 and all(. == true)' "$TMP/image.json" >/dev/null
for width in 2 3 4 5 6; do
    jq -e --argjson width "$width" '.qpdf[1] | to_entries | map(select(.value.stream.dict["/ColorSpace"] == "/DeviceRGB" and .value.stream.dict["/Width"] == $width and .value.stream.dict["/Height"] == 1)) | if length == 1 then .[0] else error("expected one RGB variant") end' "$TMP/image.json" > "$TMP/variant.json"
    object=$(jq -er '.key | capture("obj:(?<id>[0-9]+)").id' "$TMP/variant.json")
    qpdf --show-object="$object" --filtered-stream-data "$TMP/image.pdf" > "$TMP/actual-rgb"
    cmp "$TMP/variant-$width.rgb" "$TMP/actual-rgb"
    if [ -f "$TMP/variant-$width.alpha" ]; then
        mask=$(jq -er '.value.stream.dict["/SMask"] | split(" ")[0]' "$TMP/variant.json")
        qpdf --show-object="$mask" --filtered-stream-data "$TMP/image.pdf" > "$TMP/actual-alpha"
        cmp "$TMP/variant-$width.alpha" "$TMP/actual-alpha"
    else
        jq -e '.value.stream.dict["/SMask"] == null' "$TMP/variant.json" > /dev/null
    fi
done
echo 'image streams: RGB, gray, opaque RGBA, transparent RGBA/palette exact bytes passed'
