#!/bin/sh -e
oname=vegan
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' \
        -e '^Version 2.0' \
        -e '^Platform:' \
       $1 | \
    sed -e '/^> *proc\.time()$/,$d' \
        -e '/^  Natural language support but running in an English locale$/,+1d'
}

if [ "${AUTOPKGTEST_TMP}" = "" ] ; then
  AUTOPKGTEST_TMP=$(mktemp -d /tmp/${pkg}-test.XXXXXX)
  trap "rm -rf ${AUTOPKGTEST_TMP}" 0 INT QUIT ABRT PIPE TERM
fi

cp -a /usr/share/doc/${pkg}/examples/* "${AUTOPKGTEST_TMP}"
cd "${AUTOPKGTEST_TMP}"
gunzip -r *

cd vignettes
for rnw in `ls *.[rR]nw` ; do
rfile=`echo $rnw | sed 's/\.[rR]nw/.R/'`
R --no-save <<EOT
  Stangle("$rnw")
  source("$rfile", echo=TRUE)
EOT
done

cd ../tests
for htest in `ls *.R | sed 's/\.R$//'` ; do
   if [ ! -f ${htest}.Rout.save ]; then
     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 ${htest}.Rout.save_ ${htest}.Rout_
   if [ ! $? ] ; then
     echo "Test ${htest} failed"
     exit 1
   else
     echo "Test ${htest} passed"
   fi
done

rm -rf *
