#!/usr/bin/env bash

log_file=tests/interactive.log

echo Using log file "$log_file"

for testnum in $@; do
    testin=tests/$testnum.in
    testgen=tests/$testnum.gen

    echo -n "Running test $testnum"
    [ -f "$testgen" ] && echo -n " ($(cat "$testgen"))"
    echo

    handler_output=$($INTERACTIVE_HANDLER "$SOLUTION" "$GRADER" < "$testin" 2> $log_file)
    code=$?
    { read -r grader_status user_status grader_code user_code; read -r feedback; read -r scores; } <<< "$handler_output" || true
    if [ -n "$feedback" ]; then
        feedback=", feedback: $feedback"
    fi
    if [ -n "$scores" ]; then
        feedback=", scores: $scores""$feedback"
    fi
    if [ $code -ne 0 ]; then
        echo Handler crashed with return code $code
        [[ -z "$NONSTOP" ]] && exit 2
    elif [ "$grader_status" != "1" ]; then
        echo Grader crashed with return code $grader_code
        [[ -z "$NONSTOP" ]] && exit 2
    elif [[ "$user_status" != "1" || "$user_code" != "0" ]]; then
        echo Tested program crashed with return code $user_code
        [[ -z "$NONSTOP" ]] && exit 1
    elif ((grader_code < 1 || grader_code > 100)); then
        echo Grader returned $grader_code"$feedback"
        [[ -z "$NONSTOP" ]] && exit 3
    else
        echo Grader gave score $grader_code"$feedback"
    fi
done

rm -f "$log_file"
