#!/usr/bin/perl -w -I/opt/eprints2/perl_lib

#####################################################################################################
#
# This file is not part of GNU EPrints 2.
#
# Author: Antje Parnitzke, E-Mail: antje.parnitzke@dlr.de 
#  
# The script has been created in addition to the scripts import_eprints and import_subjects.
# I have tested the script with GNU Eprints 2.3.6. It works for us but check it carefully. 
#
# This script can be used to import users from an XML file into Eprints. 
# For an example of the xml file format run: export_xml archiveid user 
#
# Attention: This script does not check if the username already exists or if the usertype is valid 
#
#####################################################################################################

use EPrints::Session;
use EPrints::ImportXML;
use EPrints::User;
use strict;

if( scalar @ARGV != 2 )
{
	print STDERR "import_xml <siteid> <xmlfilename>\n";
	exit( 1 );
}

# 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_archive()->get_dataset("user"); 
if( !defined $ds )
{
	die "doh: bad dataset";
}

print "Importing from $ARGV[1] ...\n";
my $count = 0;

my $info =  { 
			ds => $ds, 
			count=>0 }; 

EPrints::ImportXML::import_file( $session , $ARGV[1] , \&deal, $ds, $info );
$count = $info->{count};

print "Done importing $count users from $ARGV[1] \n"; 
	
$session->terminate();

exit;

sub deal 
{
	my( $session , $table , $user, $info ) = @_;
	
	if( $session->get_db()->exists($info->{ds}, $user->get_value( "userid" ) ) )
	{
		print "UserID ".$user->get_value("userid")." exists! Updating the values.\n";
		$user->commit;
	}
	else 
	{
		my $newuser =EPrints::User::create_new_user($session, $info->{ds}, $user->get_data());
		print "Creating UserID: ".$newuser->get_value("userid")."\n";
		$info->{count}+=1;		
	}
}

