#!/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
export PATH

[[ -e .testdir ]] && . .testdir
if [[ -z "$TESTDIR" ]] || [[ ! -d "$TESTDIR" ]]; then
   TESTDIR=$(mktemp -d --tmpdir="/var/tmp" -t dracut-test.XXXXXX)
fi
echo "TESTDIR=\"$TESTDIR\"" > .testdir
export TESTDIR

command -v test_check &>/dev/null || test_check() {
    :
}

# terminal sequence to set color to a 'success' color (currently: green)
function SETCOLOR_SUCCESS() { echo -en '\033[0;32m'; }
# terminal sequence to set color to a 'failure' color (currently: red)
function SETCOLOR_FAILURE() { echo -en '\033[0;31m'; }
# terminal sequence to set color to a 'warning' color (currently: yellow)
function SETCOLOR_WARNING() { echo -en '\033[0;33m'; }
# terminal sequence to reset to the default color.
function SETCOLOR_NORMAL() { echo -en '\033[0;39m'; }

check_root() {
    if (( $EUID != 0 )); then
        SETCOLOR_FAILURE; echo "Tests must be run as root! Please use 'sudo'."; SETCOLOR_NORMAL
        exit 1
    fi
}

while (($# > 0)); do
    case $1 in
        --run)
            check_root
	    echo "TEST RUN: $TEST_DESCRIPTION"
	    test_check && test_run
	    exit $?;;
        --setup)
            check_root
	    echo "TEST SETUP: $TEST_DESCRIPTION"
	    test_check && test_setup
	    exit $?;;
        --clean)
	    echo "TEST CLEANUP: $TEST_DESCRIPTION"
	    test_cleanup
	    rm -fr -- "$TESTDIR"
	    rm -f -- .testdir
	    exit $?;;
        --all)
            check_root
	    echo -n "TEST: $TEST_DESCRIPTION ";
            if ! test_check 2&>test.log ; then
                SETCOLOR_WARNING
                echo "[SKIPPED]"
                SETCOLOR_NORMAL
		exit 0;
            fi
            if [ "$V" != "1" ]; then
	    (
		test_setup && test_run
		ret=$?
		test_cleanup
		rm -fr -- "$TESTDIR"
		rm -f -- .testdir
		exit $ret
	    ) </dev/null >test.log 2>&1
            else
            set -o pipefail
            (
		test_setup && test_run
		ret=$?
		test_cleanup
		rm -fr -- "$TESTDIR"
		rm -f -- .testdir
		exit $ret
	    ) </dev/null 2>&1 | tee test.log
            fi
	    ret=$?
            set +o pipefail
	    if [ $ret -eq 0 ]; then
               rm -- test.log
               SETCOLOR_SUCCESS
	       echo "[OK]"
               SETCOLOR_NORMAL
	    else
               SETCOLOR_FAILURE
	       echo "[FAILED]"
               SETCOLOR_NORMAL
	       echo "see $(pwd)/test.log"
	    fi
	    exit $ret;;
        *) break ;;
    esac
    shift
done
