#!/bin/bash

set -e

TEST_DIR=$(dirname $0)
SRC_DIR=$TEST_DIR/../src

TEST_SRC=$(find $TEST_DIR -name '*.ethlang' -and -not -name "_*")

count_total=0
count_succeeded=0

run_test_file() {
    local file=$1

    echo "- $(basename $file)"
    set +e
    output=$(deno run -A --check $SRC_DIR/main.ts $file --test)
    status=$?
    set -e

    
    if [[ status -ne 0 ]]
    then
        echo "-- failed: exit code $status --"
    fi

    if [[ status -eq 0 ]]
    then
        if grep -q '// expect:' $file
        then
            expected=$(grep '// expect:' $file | sed -E 's/\s*\/\/\s+expect:\s*(.*?)\s*/\1/g')
            if [[ $output != $expected ]]
            then
                echo "-- failed: incorrect output --"
                echo "-- expected --"
                echo "$expected"
                echo "-- actual --"
                echo "$output"
                status=1
            fi
        fi
    fi
    
    count_total=$(($count_total + 1))
    if [[ status -eq 0 ]]
    then
        count_succeeded=$(($count_succeeded + 1))
    fi
}

if [[ $1 == "" ]]
then
    for file in $TEST_SRC
    do
        run_test_file $file
    done
else
    run_test_file $1
fi

if [[ $count_succeeded -eq $count_total ]]
then
    echo "== all tests passed ($count_succeeded/$count_total passed) ==" 
else
    echo "== tests failed ($count_succeeded/$count_total passed) =="
    exit 1
fi


