#!/usr/bin/env bash
# Copyright SUSE LLC
# SPDX-License-Identifier: GPL-2.0-or-later

set -euo pipefail

prove_cmd=(prove -I .)

# skip the check for unhandled output when running in verbose mode
for arg in "$@"; do [[ $arg =~ (-v|--verbose) ]] && TEST_VERBOSE=1 && break; done
[[ ${TEST_VERBOSE:-} && $TEST_VERBOSE != 0 ]] && exec "${prove_cmd[@]}" "$@"

echo "Running prove with TAP output check ..."

# use unbuffer if available and stdout is a terminal for immediate output
[[ -t 1 ]] && unbuffer_cmd=("$(which unbuffer 2> /dev/null)") || unbuffer_cmd=()

OUTPUT=$(mktemp)
"${unbuffer_cmd[@]}" "${prove_cmd[@]}" "$@" 2>&1 | tee "$OUTPUT"

STATUS=${PIPESTATUS[0]}

if [ "$STATUS" -ne 0 ]; then
    echo "not ok - prove failed"
    exit "$STATUS"
fi

UNHANDLED=$(sed --regexp-extended \
    -e 's/\x1b\[[0-9;]*[mK]//g' \
    -e 's/\r//g' \
    -e 's/^\[[0-9]{2}:[0-9]{2}:[0-9]{2}\][[:space:]]*//' \
    -e '/x?t\/.*\.t\s*\.+/d' \
    -e '/\s*[0-9]+\.\.[0-9]+.*/d' \
    -e '/^# /d' \
    -e '/Files=.*Tests=/d' \
    -e '/Result: /d' \
    -e '/All tests successful\./d' \
    "$OUTPUT")

if [ -n "$UNHANDLED" ]; then
    echo "not ok - unhandled output found:"
    echo "$UNHANDLED"
    echo "Run with PROVE=tools/prove_wrapper to reproduce locally"
    exit 1
else
    echo "ok - no unhandled output found"
    exit 0
fi
