#!/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

hostarch=$(dpkg-architecture -qDEB_HOST_ARCH)
# Ignore single test for i386 architecture.  This is a workaround for a strange test error that occurred after r-base was compiled with -ffloat-store
if [ "$hostarch" = "i386" ] ; then
  sed -i '/pp <- profile(fit2,prof.lower=-0.2)/,$d' profbound.R*
  echo '> ' >> profbound.Rout.save
fi

# Skip test with precision error on ppc64el
# -- Graham Inggs <ginggs@ubuntu.com>  Sat, 21 May 2022 10:37:36 +0000
# Origin: https://patches.ubuntu.com/r/r-cran-bbmle/r-cran-bbmle_1.0.25-1ubuntu1.patch
hostarch=$(dpkg-architecture -qDEB_HOST_ARCH)
# 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
