#!/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\]' \
       $1 | \
    sed -e '/^> *proc\.time()$/,$d' \
        -e "/^Signif. codes:/s/[‘’]/'/g"
}

if [ "$ADTTMP" = "" ] ; then
  ADTTMP=`mktemp -d /tmp/${pkg}-test.XXXXXX`
  trap "rm -rf $ADTTMP" 0 INT QUIT ABRT PIPE TERM
fi
cd $ADTTMP
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 $ADTTMP
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 prof_newmin.R prof_spec.R
for htest in `ls *.R | sed 's/\.R$//'` ; do
   if [ "${htest}" = "doRUnit" -o "${htest}" = "RUnit-tests" ] ; 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
