#!/bin/sh

# SPDX-FileCopyrightText: © 2026 Peter Lemenkov
#
# SPDX-License-Identifier: CC0-1.0

# The GF (TeX generic font) reader is the only input module that no other
# library provides, and it had no test.  shapes.600gf is generated from
# shapes.mf (see there) and holds two glyphs: A is a square, B a triangle.

. "`dirname "$0"`/../functions"

DIR=$1

failed=""
# SVG checks the traced outline; UGS also checks the font metrics that the
# GF reader hands to the UGS writer (design size, escapement, bearings).
for code in 65 66; do
    for fmt in svg ugs; do
        autotrace -input-format gf -charcode $code $DIR/shapes.600gf -output-format $fmt -output-file $DIR/char$code.$fmt
        if ! diff -q -w --strip-trailing-cr $DIR/char$code.output.$fmt $DIR/char$code.$fmt >/dev/null; then
            failed="$failed $code.$fmt"
        fi
        rm -f $DIR/char$code.$fmt
    done
done

# A malformed font must be reported as an error (exit status 1 from the
# fatal-message handler), not terminate the process from inside the library.
# Byte 60 is the first painting command of character 65; 0xFF is no command.
cp $DIR/shapes.600gf $DIR/corrupt.600gf
printf '\377' | dd of=$DIR/corrupt.600gf bs=1 seek=60 conv=notrunc 2>/dev/null
autotrace -input-format gf -charcode 65 $DIR/corrupt.600gf -output-format svg -output-file $DIR/corrupt.svg 2>$DIR/corrupt.err
RESULT=$?
if [ $RESULT -ne 1 ] || ! grep -q "expected paint or skip or new_row" $DIR/corrupt.err; then
    failed="$failed corrupt-font(exit=$RESULT)"
fi
rm -f $DIR/corrupt.600gf $DIR/corrupt.svg $DIR/corrupt.err

# A truncated font has no postamble; it must be rejected the same way, with
# the reason in the message.
head -c 300 $DIR/shapes.600gf > $DIR/truncated.600gf
autotrace -input-format gf -charcode 65 $DIR/truncated.600gf -output-format svg -output-file $DIR/truncated.svg 2>$DIR/truncated.err
RESULT=$?
if [ $RESULT -ne 1 ] || ! grep -q "invalid signature" $DIR/truncated.err || grep -q "Cannot open input GF file" $DIR/truncated.err; then
    failed="$failed truncated-font(exit=$RESULT)"
fi
rm -f $DIR/truncated.600gf $DIR/truncated.svg $DIR/truncated.err

if [ -n "$failed" ]; then
    fail "unexpected output for:$failed"
fi
ok
