#-*- perl -*-
# Copyright (C) 2000, 2004 R Development Core Team
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	See the GNU
# General Public License for more details.
#
# A copy of the GNU General Public License is available via WWW at
# http://www.gnu.org/copyleft/gpl.html.	 You can also obtain it by
# writing to the Free Software Foundation, Inc., 51 Franklin Street,
# Fifth Floor, Boston, MA 02110-1301  USA.

# Send any bug reports to r-bugs@r-project.org

use Cwd;
use File::Basename;
use File::Path;
use Getopt::Long;
use R::Dcf;
use R::Utils;


my $revision = ' $Rev$ ';
my $version;
my $name;
$revision =~ / ([\d\.]*) /;
$version = $1;
($name = $0) =~ s|.*/||;


my @knownoptions = ("help|h", "library|l:s", "version|v");
			
GetOptions (@knownoptions) || usage();
R_version($name, $version) if $opt_version;

my $R_HOME = $ENV{'R_HOME'} ||
    die "Error: Environment variable R_HOME not found\n";
usage() if $opt_help;

my $startdir = cwd();
if($opt_library){
    chdir($opt_library) ||
	die "Error: cannot change to directory \`$opt_library'\n";
    $library = cwd();
    chdir($startdir);
} else {
    if (defined $ENV{'R_LIBS'}) {
	$library = $ENV{'R_LIBS'};
	$library =~ s/\s*;.*$//;
    } else {
	$library = $R_HOME . "/library";
    }
}

## this is the main loop over all packages to be installed
my $pkg;
foreach $pkg (@ARGV) {
      if (-d "$library/$pkg") {
  	rmtree("$library/$pkg");
      } else {
  	print "WARNING: there is no pkg \`${pkg}' in lib \`${library}'\n";
      }
}

print("\n");
## re-make the HTML indices
system("make -f $R_HOME/src/gnuwin32/MakePkg --no-print-directory RHOME=$R_HOME DPKG='$R_HOME/library' RLIB='$R_HOME/library' indices");


sub usage {
    print STDERR <<END;
Usage: R CMD $name [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 given in the
environment variable R_LIBS if this is set, and from the
default R library tree ($R_HOME/library) otherwise.

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>.
END
    exit 0;
}