#!/bin/sh

## serial 2

set -eu

top_srcdir="@abs_top_srcdir@"
VALGRIND="@VALGRIND@"

if test $# -eq 0 || test "$1" = ""; then
  echo "Missing target binary" >&2
  exit 1
fi

if test "${NOUNDEF:-}" != ""; then
  noundef="--undef-value-errors=no"
else
  noundef=""
fi

if test "${NOCHILDREN:-}" != ""; then
  trace_children="--trace-children=no"
else
  trace_children="--trace-children=yes"
fi

skip_path="$top_srcdir/run-test-valgrind.exclude"
if test -r "$skip_path" && grep -w -q "$(basename $[1])" "$skip_path"; then
  NOVALGRIND=true
fi

if test "${NOVALGRIND:-}" != ""; then
  "$@"
  ret=$?
else
  test_out="test.out~$$"
  trap "rm -f $test_out" 0 1 2 3 15
  supp_path="$top_srcdir/run-test-valgrind.supp"
  ret=0
  if test -r "$supp_path"; then
    $VALGRIND -q $trace_children --error-exitcode=213 --leak-check=full --gen-suppressions=all --suppressions="$supp_path" --log-file=$test_out $noundef "$@" || ret=$?
  else
    $VALGRIND -q $trace_children --error-exitcode=213 --leak-check=full --gen-suppressions=all --log-file=$test_out $noundef "$@" || ret=$?
  fi
  if test -s $test_out; then
    cat $test_out
    ret=1
  fi
fi
if test $ret != 0; then
  echo "Failed to run: $@" >&2
fi

exit $ret
