#!/usr/bin/perl -w -I/opt/eprints/perl_lib

######################################################################
#
#  This file is part of GNU EPrints 2.
#  
#  Copyright (c) 2000-2004 University of Southampton, UK. SO17 1BJ.
#  
#  EPrints 2 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 of the License, or
#  (at your option) any later version.
#  
#  EPrints 2 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.
#  
#  You should have received a copy of the GNU General Public License
#  along with EPrints 2; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
######################################################################

use Getopt::Long;
use Pod::Usage;
use strict;

use EPrints;

my $xml = 0;
my $version = 0;
my $verbose = 0;
my $quiet = 0;
my $force = 0;
my $purge = 1;
my $help = 0;
my $man = 0;
	
GetOptions( 
	'help|?' => \$help,
	'man' => \$man,
	'force' => \$force , 
	'version' => \$version,
	'verbose+' => \$verbose,
	'silent' => \$quiet,
	'quiet' => \$quiet
) || pod2usage( 2 );
EPrints::Utils::cmd_version( "reindex" ) if $version;
pod2usage( 1 ) if $help;
pod2usage( -exitstatus => 0, -verbose => 2 ) if $man;
pod2usage( 2 ) if( scalar @ARGV != 2 );

my $noise = 1;
$noise = 0 if( $quiet );
$noise = 1+$verbose if( $verbose );

# Set STDOUT to auto flush (without needing a \n)
$|=1;

my $session = new EPrints::Session( 1, $ARGV[0], $noise );
exit( 1 ) unless defined $session;
my $datasetid = $ARGV[1];
my $dataset = $session->get_repository->get_dataset( $datasetid );
if( !defined $dataset )
{
	$session->terminate();
	print "Exiting due to unknown dataset.\n" if( $noise >= 2 );
	exit;
}

unless( $force )
{
	if( $noise > 0 )
	{
		print "\n";
		print "You are about to recommit \"$datasetid\" in the $ARGV[0] repository.\n";
		print "This can take some time.\n\n";
		print "Number of records in set: ".$dataset->count( $session )."\n";

	}
	my $sure = EPrints::Utils::get_input_confirm( "Continue" );
	unless( $sure )
	{
		print "Aborting then.\n\n";
		$session->terminate();
		exit;
	}
}

my $fn = sub {
	my( $session, $dataset, $item ) = @_;

	if( $session->get_noise() >= 2 )
	{
		print STDERR "Committing item: ".$dataset->id()."/".$item->get_id()."\n";
	}
	$item->commit();
};

$dataset->map( $session, $fn );


$session->terminate();
print "Exiting normally.\n" if( $noise >= 2 );
exit;

