#!/bin/bash

logfile=./junit.xml

if [ -f "./vendor/bin/pest" ]; then
    runner="./vendor/bin/pest"
else
    runner="./vendor/bin/phpunit"
fi

if test -f "$logfile"; then
    echo -e "Logfile found. Searching for previously failing tests... \U23F3"

    count_failed_tests="$(xmlstarlet tr ./vendor/chrisdicarlo/phpunit-failed-runner/prune.xsl junit.xml | xmlstarlet tr --omit-decl ./vendor/chrisdicarlo/phpunit-failed-runner/count-failed.xsl)"

    if [ "$count_failed_tests" = "0" ]; then
        echo -e "No failed tests! Great job! \U1F44D \U1F389"
        rm "$logfile"
        exit 0
    else
        echo -e "Found $count_failed_tests previously failing tests, filtering... \U1F97A"
        filter=$(xmlstarlet tr ./vendor/chrisdicarlo/phpunit-failed-runner/prune.xsl junit.xml | xmlstarlet tr --omit-decl ./vendor/chrisdicarlo/phpunit-failed-runner/failed-tests.xsl); "$runner" --filter "$filter" --log-junit junit.xml
    fi
else
    echo -e "Logfile not found. Running the full test suite... \U1F91E"
    "$runner" --log-junit junit.xml
fi

exit 0
