#!/usr/bin/env bash
# autograde-logisim.sh: decide pass or fail for one Logisim-evolution circuit against one test vector.
# Usage: autograde-logisim.sh <logisim-jar> <circuit-name> <vector.txt> <circuit.circ> [timeout-seconds]
# Prints one line: PASS, or FAIL and the reason. Exit code 0 = PASS, 1 = FAIL.
# Needs: Java 21, Xvfb (xvfb-run). Logisim-evolution 5.0.0 exits with code 0 even when tests fail (F17),
# so the decision is made from the text it prints, never from its exit code.
jar=$1; circuit=$2; vector=$3; file=$4; limit=${5:-30}
# expected number of rows: lines that are not blank and not comments, minus the header line
expected=$(grep -Ev '^[[:space:]]*(#|$)' "$vector" | tail -n +2 | wc -l)
out=$(timeout -k 5 "$limit" xvfb-run -a java -jar "$jar" --no-splash -w "$circuit" "$vector" "$file" 2>&1)
code=$?
[ "$code" -eq 124 ] || [ "$code" -eq 137 ] && { echo "FAIL timeout after ${limit}s"; exit 1; }
summary=$(printf '%s\n' "$out" | grep -E '^Passed: [0-9]+, Failed: [0-9]+' | tail -n 1)
[ -z "$summary" ] && { echo "FAIL no summary line (exit $code)"; exit 1; }
passed=${summary#Passed: }; passed=${passed%%,*}; failed=${summary##*Failed: }
printf '%s\n' "$out" | grep -q 'Exception' && { echo "FAIL exception in output"; exit 1; }
[ "$failed" -ne 0 ] && { echo "FAIL $summary"; exit 1; }
[ "$passed" -ne "$expected" ] && { echo "FAIL passed $passed rows, vector has $expected"; exit 1; }
echo "PASS $summary"; exit 0
