#!/bin/sh
# run a regression test containing one or more intentional failures

if [ "$1" = "" ]; then
  echo "usage: $0 ./ccgr source-file.c [args-to-ccgr]"
  exit 0
fi
executable="$1"
srcfile="$2"
shift
shift

# read how many failure cases are in the file; expect line of form
# "// NUMERRORS n"
numcases=`grep NUMERRORS "$srcfile" | awk '{ print $3 }'`
if [ -z "$numcases" ]; then
  echo "didn't find a string of form NUMERRORS <n> in the file"
  exit 2
fi
echo "there are $numcases failure cases in this file"

# iterate through the cases; first case (0) is where no errors are present
i=0
while [ $i -le $numcases ]; do
  # generate a temporary file; first hide the ERROR tags which identify
  # the current test, then remove all remaining ERROR lines
  # (syntax for errors has parentheses so if I have >=10 cases I don't
  # run into problems where e.g. ERROR1 is a substring of ERROR10)
  echo "generating test $i"
  cat "$srcfile" | sed "s/ERROR($i)/(selected: $i)/" | grep -v ERROR > test-bad-tmp.c

  # run this through ccgr
  echo "$executable" "$@" test-bad-tmp.c
  if "$executable" "$@" test-bad-tmp.c; then
    if [ $i = 0 ]; then
      # expected success on 0th iteration
      echo "(succeeded as expected)"
    else
      # unexpected success on >0th iteration
      echo "The ${i}th iteration did not fail!  It is supposed to fail."
      exit 2
    fi
  else
    if [ $i = 0 ]; then
      # unexpected failure on 0th iteration
      echo "The 0th iteration failed! It is supposed to succeed."
      #cat test-bad-tmp.c
      exit 2
    else
      # expected failure on >0th iteration
      echo "(failed as expected)"
    fi
  fi

  # possibly bail after 0th
  if [ "$TESTBADONCE" != "" ]; then
    echo "bailing after 0th iteration because TESTBADONCE is set"
    exit 0
  fi

  i=`expr $i + 1`
done

echo "all $numcases cases in $srcfile failed as expected"
