# -*- sh -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
# 
#   http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#

test "$VERBOSE" = yes && set -x

pwd=`pwd`
t0=`echo "$0"|sed 's,.*/,,'`.tmp; tmp=$t0/$$
pid=0
test -z "$TEST_DEBUG" &&
trap 's=$?;test $pid = 0||kill -2 $pid;cd "$pwd" && rm -rf $t0 && exit $s' 0
test -z "$TEST_DEBUG" && trap '(exit $?); exit $?' 1 2 13 15

framework_failure=0
mkdir -p $tmp || framework_failure=1
cd $tmp || framework_failure=1

gen_supp=--gen-suppressions=all
# This option makes valgrind significantly slower.
full_leak_check=--leak-check=full

vg_options="
  --suppressions=$abs_srcdir/.vg-supp
  --num-callers=25
  --demangle=no
  --track-fds=yes
  $full_leak_check
  $gen_supp
  "
# configure tests for the existence of valgrind.
# If it's not available, then make $vg and vg_check no-ops.
if test x$VALGRIND = x; then
  vg=
else
  vg="libtool --mode=execute valgrind `echo $vg_options` --"
fi

vg_leak_check()
{
  local file=$1
  local fail
  # If we detect a leak, dump all output to stderr.
  grep -E '^==[0-9]+== +definitely lost: [^0]' $file \
      && { fail=1; cat $file 1>&2;
           echo "found memory leaks (see log file, $file); see above" 1>&2; }
  test "$fail" = ''
}


# Ensure 1) that there is an ERROR SUMMARY line, and
# 2) that the number of errors is 0.
# An offending line looks like this:
# ==29302== ERROR SUMMARY: 4 errors from 2 contexts (suppressed: 16 from 5)
vg_error_check()
{
  local file=$1
  local fail
  # If we detect a leak, dump all output to stderr.
  grep -E '^==[0-9]+== ERROR SUMMARY:' $file > /dev/null \
      || { fail=1; cat $file 1>&2;
           echo "no valgrind ERROR SUMMARY line in $file" 1>&2; }
  if test "$fail" = ''; then
    grep -E '^==[0-9]+== ERROR SUMMARY: [^0] ' $file \
      && { fail=1; cat $file 1>&2;
	   echo "valgrind reported errors in $file; see above" 1>&2; }
  fi
  test "$fail" = ''
}

vg_check()
{
  local file=$1
  if test x$VALGRIND != x; then
    vg_error_check $file && vg_leak_check $file
  fi
}
