#!/bin/sh

set -ue
PATH="/usr/bin:/bin"
export PATH

SEED="$(head -c24 </dev/urandom | base64)"
OUT="${AUTOPKGTEST_TMP-"${TMPDIR-/tmp}"}/out.svg"
trap 'rm -f -- "$OUT"' EXIT INT TERM

fail() {
    local msg="$1" dump="${2-y}"
    echo "ERROR: $msg" >&2
    if [ "$dump" != "n" ]; then
        echo "vvvvvvvvvvvvvvvvvvvvvvvv" >&2
        cat <"$OUT" >&2
        echo >&2
        echo "^^^^^^^^^^^^^^^^^^^^^^^^" >&2
    fi
    exit 1
}

# XXX termtosvg(1) produces empty SVG if stdin is closed or redirected
# from /dev/null (as in autopkgtest environments), so we use the
# workaround from https://github.com/nbedos/termtosvg/issues/93
tail -f </dev/null | termtosvg "$OUT" -g 80x24 -c "printf \"%s\\n\" \"$SEED\""

test -f "$OUT" || fail "$OUT: No such file" n

markup="$(grep -m1 -Eo '<\s*[0-9A-Za-z_-]+(\s|$)' <"$OUT" | tr -d "[[:blank:]]")"
[ "$markup" = "<svg" ] || fail "$OUT: Not an SVG Scalable Vector Graphics image?"

grep -Fq -e "$SEED" <"$OUT" || fail "$OUT: does not contain seed \"$SEED\""
