#!/bin/bash
# grade.sh <task> <src-dir-with-main-kotlin> -> prints JSON of passed/failed test names
T=$1; SRC=$2; S=$(dirname "$0"); W=$(mktemp -d)
cp $S/template/*.kts $W/; mkdir -p $W/src/main/kotlin $W/src/test/kotlin
cp $SRC/*.kt $W/src/main/kotlin/ 2>/dev/null; cp $S/tests/${T}Test.kt $W/src/test/kotlin/
cd $W && timeout 600 gradle test -q --offline > out.txt 2>&1; rc=$?
python3 - "$W" "$T" "$rc" <<'PY'
import sys,glob,re,json
W,T,rc=sys.argv[1:]
xml=glob.glob(f'{W}/build/test-results/test/*.xml'); res={}
for f in xml:
    s=open(f).read()
    for m in re.finditer(r'<testcase name="([^"(]+)\(?\)?"[^>]*?(/>|>(.*?)</testcase>)',s,re.S):
        res[m.group(1)]= 'failure' not in (m.group(3) or '') and 'error' not in (m.group(3) or '')
out=open(f'{W}/out.txt').read()
print(json.dumps({'compiled':bool(xml),'passed':sum(res.values()),'total':len(res),'failed':[k for k,v in res.items() if not v],'compile_error':'' if xml else out[-600:]}))
PY
rm -rf $W
