#!/bin/sh

# ${RHOME}/bin/INSTALL for checking installed add-on packages
# Usage:
#       R CMD check [options] [-l lib] pkg_1 ... pkg_n

VERSION="0.1-0"
USAGE_MSG="Usage: R CMD check [-l lib] pkg_1 ... pkg_n"
OPTS=
PKGS=
lib=${RHOME}/library

while test -n "${1}"; do
  case ${1} in
    -h|--help|-\?)
      echo "${USAGE_MSG}"; exit 0 ;;
    -V|--version)
      echo "${VERSION}"; exit 0 ;;
    --debug)
      DEBUG=true; OPTS="${OPTS} --debug" ;;
    -l)
      lib=${2}; shift ;;
    *)    
      PKGS="${PKGS} ${1}" ;;
  esac
  shift
done

if test -z "${PKGS}"; then
  echo "${USAGE_MSG}"
  exit 1
fi

if test -d ${lib} -a -w ${lib}; then
  lib=`cd ${lib}; pwd`
else
  echo "ERROR: cannot write to or create directory \`${lib}'"
  exit 2
fi

for pkg in ${PKGS}; do
  cd ${pkg}
  pkg=`basename ${pkg}`
  echo "Checking package \`${pkg}' ..."

  if test -d ${lib}/${pkg}; then
    rm -rf ${lib}/${pkg}/R-ex
  else
    echo "WARNING: package \`${pkg} not installed ... skipping"
    break
  fi

  if test -d man; then
    ${RHOME}/bin/build-help ${OPTS} --example ../${pkg} ${lib}
  else
    echo "WARNING: package \`${pkg} contains no examples ... skipping"
  fi

  test -d check || mkdir check
  cd check
  echo " Massaging examples into \`${pkg}-Ex.R' ..."
  ${RHOME}/bin/massage-Examples ${pkg} ${lib}/${pkg}/R-ex/*.R \
    > ${pkg}-Ex.R
  echo " Running examples in package \`${pkg}' ..."
  ${RHOME}/bin/R --vanilla --vsize 6 < ${pkg}-Ex.R > ${pkg}-Ex.Rout
  if test ${?} -eq 0; then
    echo " OK"
  else
    echo " ERROR"
  fi

done  
