#!/bin/bash

logfile=./testdox.xml

if test -f "$logfile"; then
    echo "Logfile found. Searching for failed tests..."
    
    failed_tests="$(xmlstarlet tr --omit-decl ./vendor/chrisdicarlo/phpunit-failed-runner/failed-tests.xsl testdox.xml)"

    if [ "$failed_tests" = "" ]; then
        echo "No failed tests!  Great job!"
    else
        ./vendor/bin/phpunit --filter "'$failed_tests'"

        # Strip out everything except the failed tests
        xmlstarlet tr ./vendor/chrisdicarlo/phpunit-failed-runner/prune.xsl testdox.xml > testdox.xml
    fi

    # If there are no more failed tests, remove the log file
    count_failed_tests="$(xmlstarlet tr --omit-decl ./vendor/chrisdicarlo/phpunit-failed-runner/count-failed.xsl testdox.xml)"

    if [ "$count_failed_tests" = "0" ]; then
        rm ./testdox.xml
    fi

else
    echo "Logfile not found. Running the full test suite..."

    ./vendor/bin/phpunit

    # Strip out everything except the failed tests
    xmlstarlet tr ./vendor/chrisdicarlo/phpunit-failed-runner/prune.xsl testdox.xml > testdox.xml
fi

exit 0
