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

######################################################################
#
#
# Copyright 2000-2008 University of Southampton. All Rights Reserved.
# 
#  This file is part of GNU EPrints 3.
#  
#  Copyright (c) 2000-2008 University of Southampton, UK. SO17 1BJ.
#  
#  EPrints 3 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 3 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 3; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
######################################################################

=pod

=head1 NAME

B<isseus_audit> - Update the issues field of all eprints.

=head1 SYNOPSIS

B<isseus_audit> I<repository_id> [B<options>] 

=head1 DESCRIPTION

This script updates the Issues field of all eprints 
in the live archive and buffer. 

This script should probably be called from your "cron" system, soon after
midnight. Something like:

 # 00:23 every morning
 23 0 * * * /opt/eprints3/bin/isseus_audit my_repo_id

This script will take longer as your repository grows, so initially you may 
want to run it more frequently, or on very large systems you might move to
just run it on Sundays.

=head1 ARGUMENTS

=over 8

=item B<repository_id> 

The ID of the eprint repository to use.

=back

=head1 OPTIONS

=over 8

=item B<--help>

Print a brief help message and exit.

=item B<--man>

Print the full manual page and then exit.

=item B<--quiet>

Be vewwy vewwy quiet. This option will supress all output unless an error occurs.

=item B<--verbose>

Explain in detail what is going on.
May be repeated for greater effect.

=item B<--version>

Output version information and exit.

=back   

=head1 AUTHOR

This is part of this EPrints 3 system. EPrints 3 is developed by Christopher Gutteridge.

=head1 VERSION

EPrints Version: eprints-3.1.3

=head1 CONTACT

For more information goto B<http://www.eprints.org/> which give information on mailing lists and the like.

Chris Gutteridge may be contacted at B<support@eprints.org>

Should you need a real world address for some reason, EPrints can be contacted in the real world at

 EPrints c/o Christopher Gutteridge
 Department of Electronics and Computer Science
 University of Southampton
 SO17 1BJ
 United Kingdom

=head1 COPYRIGHT

This file is part of GNU EPrints 3.

Copyright (c) 2000-2008 University of Southampton, UK. SO17 1BJ.

EPrints 3 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 3 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 3; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


=cut

use EPrints;

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

my $version = 0;
my $verbose = 0;
my $quiet = 0;
my $help = 0;
my $man = 0;

Getopt::Long::Configure("permute");

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

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 $file = $session->get_repository->get_conf( "config_path" )."/issues.xml";
if( -e $file )
{
	my $doc = $session->get_repository->parse_xml( $file , 1 );
	if( !defined $doc )
	{
        	EPrints::abort "Error parsing $file\n";
	}
	
	my $issues_conf = ($doc->getElementsByTagName( "issues" ))[0];
	if( !defined $issues_conf )
	{
        	EPrints::abort "Missing <issues> tag in $file\n";
	}
}
else
{
	print "No $file - skipping\n" if( $noise > 1 );
}

my $ds = $session->get_archive()->get_dataset( 'eprint' );
my $searchexp = new EPrints::SearchExpression(
       	session=>$session,
       	allow_blank => 1,
       	dataset=>$ds );
$searchexp->add_field( $ds->get_field( "eprint_status" ), 'archive buffer', 'EQ','ANY' );
my $list = $searchexp->perform_search;


# Run all available Issues plugins
my @issues_plugins = $session->plugin_list(
	type=>"Issues",
	is_available=>1 );
my $issues = {};
foreach my $plugin_id ( @issues_plugins )
{
	my $plugin = $session->plugin( $plugin_id );
	print "Running plugin: ".$plugin->get_name()."\n" if( $noise > 0 );
	my $plugin_issues = $plugin->list_issues( list=>$list );
	foreach my $itemid ( keys %{$plugin_issues} )
	{
		foreach my $issue ( @{$plugin_issues->{$itemid}} )
		{
			push @{$issues->{$itemid}}, $issue;
		}
	}
}

# Update the issues fields
print "Updating database\n" if $noise > 0;
my $now = EPrints::Time::get_iso_timestamp();
$list->map( 
		sub { 
			my( $session, $dataset, $item, $info ) = @_;
		
			my $new_issues = $issues->{$item->get_id} || [];	
			my $current_issues = $item->get_value( "item_issues" ) || [];
			my $map = {};
			foreach my $issue ( @{$new_issues} )
			{
				$issue->{id} = $issue->{type} unless( EPrints::Utils::is_set( $issue->{id} ));
				$map->{$issue->{id}} = $issue;	
			}

			my $issues_out = [];
			ISSUE: foreach my $issue ( @{$current_issues} )
			{
				my $newfound = $map->{$issue->{id}};
				if( $issue->{status} =~ m/^(reported|resolved)$/ )
				{
					print STDERR "Odd issue reported on item ".$item->get_id." - ".$issue->{id}." has status of ".$issue->{status}." so can't be auto-modified!\n" if( $noise > 0 );
					next ISSUE;
				}
				if( defined $newfound )
				{
					# issue used to exist, and still exists

					# reopen it if needed
					if( $issue->{status} eq "autoresolved" ) 
					{ 
						$issue->{status} = "discovered"; 
						$issue->{timestamp} = $now;
					}
					# (if it's 'ignored' then leave it alone)
					$issue->{description} = EPrints::XML::to_string( 
						$newfound->{description} );
					delete $map->{$issue->{id}};
				}
				else
				{
					# issue used to exist, but now doesn't.
					$issue->{timestamp} = $now;
					$issue->{status} = "autoresolved";
				}
			}
			foreach my $id ( keys %{$map} )
			{
				my $issue = $map->{$id};	
				$issue->{timestamp} = $now;
				$issue->{status} = "discovered";
				push @{$current_issues}, $issue;
			}
			# add new issues
			$item->set_value( "item_issues", $current_issues );
			$item->commit;
		},
	);
print "Done updating database\n" if $noise > 0;


$list->dispose;


#####################################

$session->terminate();
exit;


