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


use EPrints::Session;

use File::Copy;
use File::Find;
use strict;
use Getopt::Long;
use Pod::Usage;

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

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

our $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 $b_ds = $session->get_archive->get_dataset( 'buffer' );
my $a_ds = $session->get_archive->get_dataset( 'archive' );

my $searchexp = new EPrints::SearchExpression(
		session=>$session, dataset=>$b_ds );

# Get today's date
my( $year, $month, $day ) = EPrints::Utils::get_date( time );
# Substract a month		
$month--;

# Check for year "wrap"
if( $month==0 )
{
		$month = 12;
		$year--;
}
		
# Ensure two digits in month
while( length $month < 2 )
{
	$month = "0".$month;
}
my $last_month = $year."-".$month."-".$day;

# Add the field searching for stuff from a month onwards
$searchexp->add_field( 
			$b_ds->get_field( 'datestamp' ),
			'-'.$last_month );

my $searchid = $searchexp->perform_search;

my @records = $searchexp->get_records;
$searchexp->dispose();

print "Finding items older than: $last_month\n";
foreach my $eprint ( @records )
{
	print "Moving ".$r->get_value( "eprintid" ).":". $r->get_value( "title" )." to live archive... ";
	if ( $eprint->move_to_archive() )
	{
		print "OK\n";
	}
	else
	{
		print "ERROR\n";
	}
}
print "done\n";




$session->terminate();
	
exit;
