#!/bin/sh
# Regression test for the [Mayhem] crash bugs (Debian bugs #715579, #715580,
# #715581, #715582 and #715583).  These reproduce the malformed command
# lines found by the Mayhem fuzzing project: each ANTs tool is fed a
# command line with non-existent input files and/or missing arguments.  The
# tools must not crash (segmentation fault, exit status 139); they are
# expected to report an error and exit cleanly (possibly with a non-zero
# status) instead.
set -e

BINDIR=/usr/lib/ants

run_case() {
  name="$1"
  tool="$2"
  args="$3"
  echo "Running $name (tool: $tool, args: $args) ..."
  set +e
  eval "env -i MALLOC_CHECK_=0 '$BINDIR/$tool' $args" </dev/null >/tmp/mayhem-$name.out 2>&1
  rc=$?
  set -e
  if [ "$rc" -ge 128 ]; then
    echo "  FAIL: $tool was killed by a signal (status $rc)"
    sed 's/^/    /' /tmp/mayhem-$name.out | head -10
    return 1
  else
    echo "  OK: $tool handled $name without crashing (status $rc)"
    return 0
  fi
}

fail=0
run_case ANTS ANTS "'2' 'A' 'A'" || fail=1
run_case ANTSIntegrateVectorField ANTSIntegrateVectorField "'AAAAAAAAAA' 'AA' 'AA'" || fail=1
run_case ANTSUseDeformationFieldToGetAffineTransform \
  ANTSUseDeformationFieldToGetAffineTransform "' AAAAAAAAA' '.0'" || fail=1
run_case ANTSUseLandmarkImagesToGetAffineTransform \
  ANTSUseLandmarkImagesToGetAffineTransform "'AAAAAAAAAA' 'AA' 'AA'" || fail=1
run_case Atropos Atropos "'-a'" || fail=1

if [ "$fail" -ne 0 ]; then
  echo "At least one ANTs tool still crashes on malformed input."
  exit 1
fi
echo "All malformed-input testcases handled without crashing."
