#!/bin/sh -e

export LC_ALL=C.UTF-8

# R DESCRIPTION files use the debian control file format
# (see R package manual 1.1.1)
pkgname=$(grep-dctrl -s Package -n '' DESCRIPTION)
debname=$(grep-dctrl -s Source -n '' debian/control)
bioc=$(grep-dctrl -s biocViews -n '' DESCRIPTION)

# Test 1: loading
echo "Test: Try to load the R library ${pkgname}"
R --no-save -e "library('${pkgname}')"

##########
echo "Other tests are currently unsupported!"
echo "They will be progressively added."
exit 0
##########

# Create temp environment for testing
if [ "$AUTOPKGTEST_TMP" = "" ] ; then
  AUTOPKGTEST_TMP=`mktemp -d /tmp/${debname}-test.XXXXXX`
  trap "rm -rf $AUTOPKGTEST_TMP" 0 INT QUIT ABRT PIPE TERM
fi

cp -a * $AUTOPKGTEST_TMP
cd $AUTOPKGTEST_TMP

# Test 2: bioc
if [ "$bioc" != "" ] ; then
  echo "Bioconductor package detected"
  echo "Test: Run the Bioconductor testing workflow for ${pkgname}"
  R --no-save -e "BiocGenerics:::testPackage('${pkgname}')"
  exit 0
fi

# Test 3: testthat
if [ -f "tests/testthat.R" ] ; then
  echo "Test: Run the testthat workflow for ${pkgname}"
  cd tests
  R --no-save < testthat.R
  exit 0
fi

# Test 5: RUnit
NBTEST=`find tests -type f -name "*.R" | wc -l`
if [ "$NBTEST" -gt "0" ] ; then
  echo "Test: Run the RUnit workflow for ${pkgname}"
  cd tests
  for testfile in *.R; do
    echo "Start: ${testfile}"
    R --no-save < ${testfile}
  done
  exit 0
fi

# Test 6: vignettes
if [ -d "vignettes" ] ; then
 echo "Test: Try to build vignettes"
  for vignette in $(find vignettes -iname '*.rnw' -or -iname '*.rmd'); do
    echo "Test: Try to build VIGNETTE $vignette"
    R CMD Sweave $vignette
  done
  exit 0
fi


