#!/bin/sh -e

oname=bbmle
pkg=r-cran-`echo $oname | tr '[A-Z]' '[a-z]'`

# The saved result files do contain some differences in metadata and we also
# need to ignore version differences of R
filter() {
    grep -v -e '^R version' \
        -e '^Copyright (C)' \
        -e '^R : Copyright 20' \
        -e '^R Under development (unstable)' \
        -e '^Platform:' \
        -e '^ISBN 3-900051-07-0' \
        -e '^$' \
        -e 'Natural language support but running in an English locale' \
        -e '^Loading required package: stats4' \
        -e '^\[Previously saved workspace restored\]' \
        -e '^In optim(par =' \
       $1 | \
    sed -e '/^> *proc\.time()$/,$d' \
        -e "/^Signif. codes:/s/[‘’]/'/g"
}

if [ "$AUTOPKGTEST_TMP" = "" ] ; then
  AUTOPKGTEST_TMP=`mktemp -d /tmp/${pkg}-test.XXXXXX`
  trap "rm -rf $AUTOPKGTEST_TMP" 0 INT QUIT ABRT PIPE TERM
fi
cd $AUTOPKGTEST_TMP
if [ 0 -eq 1 ] ; then # try to use RUnit - but this does not do anything :-(
  mkdir inst
  cd inst
  cp -a /usr/lib/R/site-library/${oname}/unitTests .
  cd ..
fi
cp -a /usr/share/doc/${pkg}/tests $AUTOPKGTEST_TMP
find . -name "*.gz" -exec gunzip \{\} \;
cd tests
if [ 0 -eq 1 ] ; then # try to use RUnit - but this does not do anything :-(
  # This does not test anything - no idea why
  RCMDCHECK=FALSE R --vanilla --slave < doRUnit.R
fi

# skip tests which have no saved results
rm -f boundstest.R impsamp.R prof_newmin.R prof_spec.R

# Ignore single test on armhf
hostarch=$(dpkg-architecture -qDEB_HOST_ARCH)

if [ "$hostarch" = "armhf" ] ; then
    rm -f formulatest.R glmcomp.R methods.R mortanal.R profbound.R
fi

# Skip test with precision error on ppc64el
if [ "$hostarch" = "ppc64el" ] ; then
    rm -f formulatest.R
fi

for htest in `ls *.R | sed 's/\.R$//'` ; do
   if [ "${htest}" = "doRUnit" -o "${htest}" = "RUnit-tests" -o "${htest}" = "optimize" ] ; then
      # This is no separate test but should trigger all test (but fails to do so for whatever reason
      continue
   fi
   if [ "${htest}" = "optimx" ] ; then
      # Needs https://cran.r-project.org/web/packages/optimx/ which is not packaged yet
      continue
   fi
   LC_ALL=C R --no-save < ${htest}.R 2>&1 | tee > ${htest}.Rout
   filter ${htest}.Rout.save > ${htest}.Rout.save_
   filter ${htest}.Rout > ${htest}.Rout_
   diff -u --ignore-space-change ${htest}.Rout.save_ ${htest}.Rout_
   if [ ! $? ] ; then
     echo "Test ${htest} failed"
     exit 1
   else
     echo "Test ${htest} passed"
   fi
done
