#!/bin/sh
SAMPLES=$(find playground/samples -name "*.newt")
# NCC="bun run newt.js"
NCC="node newt.js"
total=0
failed=0
for fn in tests/*.newt ; do
  total=$((total + 1))
  echo Test $fn
  bn=$(basename $fn)
  if [ -f ${fn}.golden ]; then
    $NCC $fn -o out.js > tmp/${bn}.compile
  else
    # we've dropped support for compiling things without main for now.
    $NCC $fn > tmp/${bn}.compile
  fi
  cerr=$?
  if [ -f ${fn}.fail ]; then
    if ! diff -q tmp/${bn}.compile ${fn}.fail; then
        echo "Compile failure mismatch for $fn"
        diff ${fn}.fail tmp/${bn}.compile
        failed=$((failed + 1))
        if [ $1 = "--fix" ]; then
          cp tmp/${bn}.compile ${fn}.fail
        fi
        continue
    fi
  elif [ $cerr != "0" ]; then
    echo Compile failed for $fn
    failed=$((failed + 1))
    cat tmp/${bn}.compile

    continue
  fi
  # if there is a golden file, run the code and compare output
  if [ -f ${fn}.golden ]; then
    node out.js > tmp/${bn}.out
    if [ $? != "0" ]; then
      echo Run failed for $fn
      failed=$((failed + 1))
      continue
    fi
    if ! diff -q tmp/${bn}.out ${fn}.golden; then
      echo "Output mismatch for $fn"
      diff ${fn}.golden tmp/${bn}.out
      failed=$((failed + 1))
      if [ $1 = "--fix" ]; then
        cp tmp/${bn}.out ${fn}.golden
      fi
    fi
  fi
done
echo "Total tests: $total"
echo "Failed tests: $failed"

