# Copyright 2020 FireEye, Inc. and Citrix Systems, Inc.

readonly current_directory="$( cd "$(dirname "$0")" ; pwd -P )";
readonly scanner_path="$current_directory/../ioc-scanner-CVE-2019-19781.sh";

run_tests() {
    local readonly path="$1";
    local readonly depth="${2:-}";

    for test in "$path/"*; do
        # consider the subdirectories.
        if [ ! -d "$test" ]; then
            continue
        fi

        if [ -f "$test/test.sh" ]; then
            echo "runnning test: $depth $(basename "$test")";
            # setup the test
            "$test/test.sh";
            output=$("$scanner_path" "$test" --verbose 2>&1);
        elif [ -f "$test/.test" ]; then
            echo "runnning test: $depth $(basename "$test")";
            output=$("$scanner_path" "$test" --verbose 2>&1);
        else
            echo "runnning test: $depth $(basename "$test")";
            run_tests "$test" "$depth  ";
            continue;
        fi
        scanner_status="$?";

        if [ "$scanner_status" != 0 ]; then
            echo "failed: $test";
            echo "$output";
            exit 1;
        fi

        if ! echo "$output" | grep -q "^\(MATCH\|SCANNING\|FAILED\)"; then
            echo "failed: did not match as expected";
            exit 1;
        fi
    done;
}

run_tests "$current_directory";