#!/usr/bin/env bash

set -exo pipefail

if [ ! -d "$PWD/build" ]; then
  echo "Must have built ONNX in build/"
  exit 1
fi

export PYTHONPATH=$PWD/build
export PYTHONUNBUFFERED=1

MODEL_AUTOSCHEDULER="$(python -c  "import halide; print(halide.install_dir())")/lib/libautoschedule_adams2019.so"
export MODEL_AUTOSCHEDULER

OUTFILE="halide_as_onnx_backend_failures_table.py"

rm -f "$OUTFILE"
echo "" > "$OUTFILE"

(
  echo "# -+-+- THIS FILE WAS GENERATED BY update_failures_table.sh DO NOT EDIT -+-+- #"
  echo "# fmt: off"
  echo "HALIDE_ONNX_KNOWN_TEST_FAILURES = ["
  python halide_as_onnx_backend_test.py 2>&1  \
   | awk '
     /^(ERROR|FAIL): test_/ {
         fail_type = $1
         # Extract test name, remove _cpu suffix and replace with _.*
         match($0, /test_[a-zA-Z0-9_]+/)
         test_name = substr($0, RSTART, RLENGTH)
         gsub(/_cpu$/, "_.*", test_name)
     }
     /^[A-Za-z][A-Za-z0-9]*Error: / {
         # Extract error message
         sub(/^[A-Za-z][A-Za-z0-9]*Error: /, "", $0)
         error_msg = $0
         print "    (\"" fail_type "\", \"" error_msg "\", r\"" test_name "\"),"
         fflush()
     }' \
   | sort || true
  echo "]"
  echo "# fmt: on"
) > "$OUTFILE.tmp"

mv "$OUTFILE.tmp" "$OUTFILE"
