#!/bin/sh

set -e

# webpng and gdcmpgif work whether or not libgd supports the gd and gd2 formats
cp debian/tests/testfile.png $AUTOPKGTEST_TMP/webpng.png
webpng -d $AUTOPKGTEST_TMP/webpng.png | grep -q "^Width: 100 Height: 100 " &&
    webpng -i y $AUTOPKGTEST_TMP/webpng.png &&
    file $AUTOPKGTEST_TMP/webpng.png | grep -q "PNG image data, 100 x 100, .*, interlaced" || {
        echo "webpng failed on $AUTOPKGTEST_TMP/webpng.png:"
        ls -l $AUTOPKGTEST_TMP/webpng.png
        file $AUTOPKGTEST_TMP/webpng.png
        false
    }

gdcmpgif debian/tests/testfile.gif debian/tests/testfile.gif | grep -q "^%gdcmpgif: OK" || {
    echo "gdcmpgif does not find debian/tests/testfile.gif equal to itself"
    false
}

# The converters below only work when libgd is built with --enable-gd-formats
if pngtogd debian/tests/testfile.png $AUTOPKGTEST_TMP/probe.gd 2>&1 | grep -q "GD image support has been disabled"; then
    echo "libgd is built without the gd and gd2 formats, skipping the converters"
    exit 0
fi

DATA=$(cat <<EOF
pngtogd gdtopng testfile.png image/png
pngtogd2 gd2topng testfile.png image/png 1024 2
giftogd2 gd2togif testfile.gif image/gif 1024 2
EOF
)
echo "$DATA" | while read tool reverse source_file expected_mime args; do
    $tool debian/tests/$source_file $AUTOPKGTEST_TMP/$source_file.gd $args
    $reverse $AUTOPKGTEST_TMP/$source_file.gd $AUTOPKGTEST_TMP/1-$source_file
    rm $AUTOPKGTEST_TMP/$source_file.gd
    $tool $AUTOPKGTEST_TMP/1-$source_file $AUTOPKGTEST_TMP/$source_file.gd $args
    $reverse $AUTOPKGTEST_TMP/$source_file.gd $AUTOPKGTEST_TMP/$source_file

    test "$(stat -c "%s" $AUTOPKGTEST_TMP/$source_file)" -gt 1000 && file -i $AUTOPKGTEST_TMP/$source_file | grep -q $expected_mime  &&
        diff -q $AUTOPKGTEST_TMP/$source_file $AUTOPKGTEST_TMP/1-$source_file || {
            echo "File $AUTOPKGTEST_TMP/$source_file unsatisfactory:"
            ls -l $AUTOPKGTEST_TMP/$source_file
            file -i $AUTOPKGTEST_TMP/$source_file
            false
        }
    
done
    
