package EPrints::Plugin::Export::CheckRevisions;

#
# This is a utility Export plugin that check revision files and record consistency
# It's a modification of RemoveRevisions.pm plugin ( http://files.eprints.org/615 )
#
# 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 3 of the License, 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.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

use Data::Dumper;
use EPrints::Plugin::Export;

@ISA = ( "EPrints::Plugin::Export" );

use strict;

sub new
{
	my( $class, %opts ) = @_;

	my $self = $class->SUPER::new( %opts );

	$self->{name} = "Remove all but the latest 5 revisions";
	$self->{accept} = [ 'list/eprint' ];
	$self->{visible} = "staff";
	$self->{advertise} = 0;
	$self->{suffix} = ".txt";
	$self->{mimetype} = "text/plain; charset=utf-8";
	$self->{arguments}->{write} = 0;
	
	return $self;
}


sub output_list
{
	my( $self, %opts ) = @_;

	my $rc = "";
	my $f = defined $opts{fh} ?
		sub { print {$opts{fh}} @_ } :
		sub { $rc .= join('',@_) };

	my $history_ds = $self->{session}->dataset( "history" );

	$opts{list}->map(sub {
		my( undef, undef, $eprint ) = @_;

                &$f( $eprint->id . "\n");

		my $write = $opts{write};

		$history_ds->search(
			filters => [
				{ meta_fields => [qw( datasetid )], value => "eprint" },
				{ meta_fields => [qw( objectid )], value => $eprint->id },
			],
			custom_order => "-timestamp/-historyid"
		)->map(sub {
			my( undef, undef, $history ) = @_;


			my $file = $history->stored_file( "dataobj.xml" );
 

			return if !$file;
                    
                        if ($file->get_value("hash") ne  $file->generate_md5()) {
                            &$f( $eprint->id(), ":", $file->id, ",DEL\n" );
                            EPrints::DataObj::remove($file) if ($write);
                        } else {
                            &$f( $eprint->id(), ":", $file->id, ",OK\n" );
                        }


		});
	});

	return $rc;
}

1;
