#!/bin/sh

dir=`dirname "$0"`

# change directory to $AUTOPKGTEST_TMP
cd "${AUTOPKGTEST_TMP}"

cleanup() {
  ex=$?
  rm -f testvalgrind.bin mustfail.log
  exit "${ex}"
}
trap "cleanup" EXIT TERM INT

# test if valgrind package exists
echo 'test if valgrind package exists ... START'
if which valgrind >/dev/null; then
  echo 'test if valgrind package exists ... OK'
else
  echo 'test if valgrind package exists ... FAILED, skipping tests'
  exit 77
fi

# try to install libmceliece1-dbgsym
(
  exec 2>&1
  dpkg -l libmceliece1-dbgsym >/dev/null && exit 0
  apt-get update
  apt-get -y install libmceliece1-dbgsym
) || :

# test if libmceliece1-dbgsym package exists
echo 'test if libmceliece1-dbgsym package exists ... START'
if dpkg -l libmceliece1-dbgsym 1>/dev/null 2>&1; then
  echo 'test if libmceliece1-dbgsym package exists ... OK'
else
  echo 'test if libmceliece1-dbgsym package exists ... NOT EXIST (valgrind will not print debug symbols)'
fi

ulimit -s unlimited

CC="cc -O2"
VALGRIND="env valgrind_multiplier=1 valgrind -q --max-stackframe=16777216 --error-exitcode=99"

echo 'compilation ... START'
if ${CC} -o testvalgrind.bin "${dir}/testvalgrind.c" -lmceliece 2>&1; then
  echo 'compilation ... OK'
else
  echo 'compilation ... FAILED, skipping tests'
  exit 77
fi

# test if valgrind works, valgrind must show tracebacks:"
#  mustfail_keypair ... Conditional jump or move depends on uninitialised value(s)"
#  mustfail_enc ....... Use of uninitialised value"
#  mustfail_dec ....... Use of uninitialised value"
${VALGRIND} ./testvalgrind.bin mustfail ref >mustfail.log 2>&1
RET=$?
if [ $RET -eq 99 ]; then
  echo 'test if valgrind works ... START'
  # uncomment to print valgrind traceback
  # cat mustfail.log
  echo 'test if valgrind works ... OK'
elif [ $RET -eq 0 ]; then
  echo 'test if valgrind works ... FAILED, skipping tests'
  exit 77
else
  cat mustfail.log
  echo 'test if valgrind works ... FAILED, but with exit code not from valgrind, skipping tests'
  exit 77
fi

# main test
EX=0
for primitive in 6960119 6688128 8192128 460896 348864; do
  for variant in '' f; do
    for implname in vec avx; do
      echo "mceliece${primitive}${variant} ${implname} ... START"
      ${VALGRIND} ./testvalgrind.bin "${primitive}${variant}" "${implname}"
      RET=$?
      if [ $RET -eq 0 ]; then
        echo "mceliece${primitive}${variant} ${implname} ... OK"
      elif [ $RET -eq 10 ]; then
        echo "mceliece${primitive}${variant} ${implname} ... NOT AVAILABLE (skipping)"
      else
        echo "mceliece${primitive}${variant} ${implname} ... FAILED" >&2
        EX=1
      fi
    done
  done
done

exit "${EX}"
