#!/usr/bin/env bash
set -o pipefail
exitcode=0

echo The following JSON files should be converted to canonical form...
for filename in testdata/*.json; do
    echo Generating canonical JSON for file $filename...

    canonical_digest=$(canonjson $filename | sha256sum)
    this_digest=$(cargo run $filename | sha256sum)

    echo SHA256 generated by the Go canonical JSON implementation: $canonical_digest
    echo SHA256 generated by the Rust canonical JSON implementation: $this_digest

    if [ "$canonical_digest" != "$this_digest" ]; then
        echo ERROR: digests not equal
        exitcode=1
    fi

done

echo
echo
echo The following JSON files contain invalid elements for canonical JSON, so their canonicalization should fail...
for filename in testdata/errors/*.json; do
    echo Generating canonical JSON for file $filename...

    canonjson $filename
    cjs=$?
    cargo run $filename
    ts=$?

    echo Exit code of the Go canonical JSON implementation for non-valid canonical JSON: $cjs
    echo Exit code of the Rust canonical JSON implementation for non-valid canonical JSON: $ts

    if [ "$ts" -eq 0 ] || [ "$cjs" -eq 0 ]; then
        echo ERROR: This should not be valid canonical JSON
        exitcode=1
    fi

done

echo
echo
if [ "$exitcode" -eq 0 ]; then
    echo SUCCESS
    exit 0
else
    echo ERROR
    exit 1
fi