#! /bin/sh
#
# ${R_HOME}/bin/REMOVE for removing add-on packages

revision='$Rev$'
version=`set - ${revision}; echo ${2}`
version="R add-on package remover ${version}

Copyright (C) 2000-2006 The R Core Development Team.
This is free software; see the GNU General Public License version 2
or later for copying conditions.  There is NO warranty."

usage="Usage: R CMD REMOVE [options] pkgs

Remove the add-on packages specified by pkgs.  The library tree to
remove from can be specified via '--library'.  By default, packages are
removed from the library tree rooted at the first directory in
.libPaths() for an R session run in the current environment.

Options:
  -h, --help		print short help message and exit
  -v, --version		print REMOVE version info and exit
  -l, --library=LIB	remove packages from library tree LIB

Report bugs to <r-bugs@r-project.org>."

GETWD='@GETWD@'
R_EXE="${R_HOME}/bin/R"

lib=
pkgs=

while test -n "${1}"; do
  case ${1} in
    -h|--help)
      echo "${usage}"; exit 0 ;;
    -v|--version)
      echo "${version}"; exit 0 ;;
    -l)
      lib="${2}"; shift ;;
    --library=*)
      lib=`echo "${1}" | sed -e 's/[^=]*=//'` ;;
    *)
      pkgs="${pkgs} ${1}" ;;
  esac
  shift
done

if test -z "${pkgs}"; then
  echo "ERROR: no packages specified"
  exit 1
fi

if test -z "${lib}"; then
  lib=`echo "cat(.libPaths()[1])" | \
    R_DEFAULT_PACKAGES=NULL "${R_EXE}" --no-save --slave`
  echo "Removing from library '$lib'"
fi


if test -d "${lib}" -a -w "${lib}"; then
  lib=`cd "${lib}" && ${GETWD}`
else    
  echo "ERROR: cannot cd to or remove from directory '${lib}'"
  exit 2
fi    

cd "${lib}"
for pkg in ${pkgs}; do
  pkg=`basename "${pkg}"`	# in case someone gave a path ...
  if test -d "${pkg}"; then
    rm -rf "${pkg}"
  else
    echo "WARNING: there is no pkg '${pkg}' in lib '${lib}'"
    continue
  fi
done

if test "${lib}" = `cd "${R_HOME}/library" && ${GETWD}`; then
  echo "tools:::unix.packages.html(.Library, docdir=\"${R_DOC_DIR}\")" | \
    R_DEFAULT_PACKAGES=NULL LC_ALL=C "${R_HOME}/bin/R" --vanilla >/dev/null
  cat "${R_HOME}"/library/*/CONTENTS \
    > "${R_DOC_DIR}"/html/search/index.txt
fi

### Local Variables: ***
### mode: sh ***
### sh-indentation: 2 ***
### End: ***