#!/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 EPrints;

use strict;

if( scalar @ARGV != 3 )
{
	print STDERR "import_xml <siteid> <dataset> <xmlfilename>\n";
	exit( 1 );
}
#cjg Nice Command Options
#cjg man page

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

my $session = new EPrints::Session( 1 , $ARGV[0] );
exit( 1 ) unless( defined $session );


my $ds = $session->get_repository->get_dataset( $ARGV[1] ); 
if( !defined $ds )
{
	die "doh: bad dataset";
}
my $dostatic = $ARGV[1] eq "archive" || $ARGV[1] eq "deletion";

# Using a local so it appears in subroutines. Normally I would
# try and avoid doing this.
my $info =  { 
	update_abstracts => [],
	ds => $ds 
};

EPrints::ImportXML::import_file( $session , $ARGV[2] , \&deal, $ds, $info );

if( $dostatic )
{
	# Update all the abstract pages of these records and any which
	# they impact (later versions etc)
	my %done = ();
	foreach( @{$info->{update_abstracts}} )
	{
		next if( $done{$_} );
		my $eprint = EPrints::DataObj::EPrint->new( $session, $_, $info->{ds} );
		$eprint->generate_static();
		$done{$_} = 1;
	}
}
	
$session->terminate();

exit;

sub deal 
{
	my( $session , $table , $eprint, $info ) = @_;

	if( $session->get_database->exists( $info->{ds} , $eprint->get_value( "eprintid" ) ) )
	{
		print  "EXISTS!\n";
		$eprint->commit;
	}
	else 
	{
		print  "NOT EXISTS!\n";
		#cjg needs a userid
		$eprint = $info->{ds}->create_object( $session, $eprint->get_data );
	}
	foreach( $eprint->get_all_related() )
	{
		push @{$info->{update_abstracts}}, $_->get_value( "eprintid" );
	}
	push @{$info->{update_abstracts}}, $eprint->get_value( "eprintid" );
}

