###########################################################################
#
# docsave.pm
# A component of the Greenstone digital library software
# from the New Zealand Digital Library Project at the 
# University of Waikato, New Zealand.
#
# Copyright (C) 1999 New Zealand Digital Library Project
#
# 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 2 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, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
###########################################################################

# This document processor saves a document in the 
# archives directory of a collection (as xml)

use strict;
no strict 'refs';

package docsave;

eval {require bytes};

use arcinfo;
use docproc;
use util;


sub BEGIN {
    @docsave::ISA = ('docproc');
}


sub calcoutputdir 
{
    my ($service,$collectdir,$outhandle) = @_;

    my $output_dir = undef;

    if (($service eq "import") || ($service eq "unbuild")) {
	$output_dir = &util::filename_cat ($collectdir, "archives");
    }
    elsif ($service eq "export") {
	$output_dir = &util::filename_cat($collectdir, "export");
    }
    else {
	print $outhandle "docsave::calcoutputdir did not recognise service ";
	print $outhandle " '$service'. No output directory set.\n";
    }

    return $output_dir;
}


sub new {
    my ($class, $collection, $info, $verbosity, 
	$gzip, $groupsize, $outhandle, $service, $saveas) = @_;
    my $self = new docproc ();
    
    my $collectdir = $ENV{'GSDLCOLLECTDIR'};

    $outhandle = 'STDERR' unless (defined $outhandle);
    $service   = "import" unless (defined $service);
    $saveas    = "GA" unless (defined $saveas);
    $groupsize = 1 unless (defined $groupsize);

    $self->{'collection'} = $collection;

    $self->{'output_info'} = $info;
    $self->{'output_dir'} = undef;

    $self->{'verbosity'} = $verbosity;
    $self->{'gzip'} = $gzip;
    $self->{'keepimportstructure'} = 0;
    $self->{'groupsize'} = $groupsize;
    $self->{'gs_count'}  = 0;

    $self->{'outhandle'} = $outhandle;
    $self->{'service'}   = $service;
    $self->{'saveas'}    = $saveas;

    $self->{'sortmeta'} = undef;
    
    return bless $self, $class;
}



sub setoutputdir 
{
    my $self = shift @_;
    my ($output_dir) = @_;

    &util::mk_all_dir ($output_dir) unless -e $output_dir;

    $self->{'output_dir'} = $output_dir;
}

sub getoutputinfo 
{
    my $self = shift (@_);

    return $self->{'output_info'};
}

sub getoutputdir 
{
    my $self = shift (@_);

    return $self->{'output_dir'};
}


sub set_sortmeta {
    my $self = shift (@_);
    my ($sortmeta, $removeprefix, $removesuffix) = @_;
    
    $self->{'sortmeta'} = $sortmeta;
    if (defined ($removeprefix) && $removeprefix ) {
	$removeprefix =~ s/^\^//; # don't need a leading ^
	$self->{'removeprefix'} = $removeprefix;
    }
    if (defined ($removesuffix) && $removesuffix) {
	$removesuffix =~ s/\$$//; # don't need a trailing $
	$self->{'removesuffix'} = $removesuffix;
    }
}

sub process {
    my $self = shift (@_);
    my ($doc_obj) = @_;
 
    my $outhandle = $self->{'outhandle'};
    my $service = $self->{'service'};

    # Define the SaveAs Type
    my $save_as = $self->{'saveas'};
    my $collection = $self->{'collection'};

    # set the lastmodified time before we write it out.
    $doc_obj->set_lastmodified();

    if ($self->{'groupsize'} > 1) {
	$self->group_process ($doc_obj);
	return;
    }

    my $OID = $doc_obj->get_OID();
    $OID = "NULL" unless defined $OID;

    my $top_section = $doc_obj->get_top_section();

    # get document's directory
    my $doc_dir = $self->get_doc_dir ($OID, $doc_obj->get_source_filename());

    # groupsize is 1 (i.e. one document per XML file) so sortmeta 
    # may be used
    
    my $output_info = $self->getoutputinfo();
    return if (!defined $output_info);

    my $output_dir = $self->getoutputdir();
    my $working_dir = &util::filename_cat ($output_dir, $doc_dir);

    # copy all the associated files, add this information as metadata
    # to the document
    if ($save_as eq "DSpace") {

	# Genereate handle file 
	# (Note: this section of code would benefit from being restructured)
	my $doc_handle_file = &util::filename_cat ($working_dir, "handle");

	my $env_hp = $ENV{'DSPACE_HANDLE_PREFIX'};
	my $handle_prefix = (defined $env_hp) ? $env_hp : "123456789";

	if (!open(OUTDOC_HANDLE,">$doc_handle_file")){
	    print $outhandle "docsave::process could not write collection handle to file $doc_handle_file\n";
	    return;
	} 

	my ($handle) = ($doc_dir =~ m/^(.*)\.dir$/);
	print OUTDOC_HANDLE "$handle_prefix/$handle\n";

	close OUTDOC_HANDLE;

	# Generate contents file
	my $doc_contents_file = &util::filename_cat ($working_dir, "contents");
	
	if (!open(OUTDOC_CONTENTS,">$doc_contents_file")){
	    print $outhandle "docsave::process could not write collection contents to file $doc_contents_file\n";
	    return;
	} 
	$self->process_assoc_files ($doc_obj, $doc_dir, 'docsave::OUTDOC_CONTENTS');

	close OUTDOC_CONTENTS;

    } else {
	$self->process_assoc_files ($doc_obj, $doc_dir, '');
    }
        
    # Save the document in the requested 'save_as' format

    if ($save_as eq "GA") {

	my $doc_file = &util::filename_cat ($working_dir, "doc.xml");

	if (!open (OUTDOC, ">$doc_file")) {
	    print $outhandle "docsave::process could not write to file $doc_file\n";
	    return;
	}
	
	# save this document
	$self->output_xml_header('docsave::OUTDOC');
	$doc_obj->output_section('docsave::OUTDOC',$top_section);
	$self->output_xml_footer('docsave::OUTDOC');
	
	close OUTDOC;
    } 
    elsif ($save_as eq "METS") {
	
	my $doc_txt_file = &util::filename_cat ($working_dir,"doctxt.xml");	

	if (!open(OUTDOC_TXT, ">$doc_txt_file")){
	    print $outhandle "docsave::process could not write to file $doc_txt_file\n";
	    return;
	}
	
	$self->output_txt_xml_header('docsave::OUTDOC_TXT');
	$doc_obj->output_txt_section('docsave::OUTDOC_TXT', $top_section);
	$self->output_txt_xml_footer('docsave::OUTDOC_TXT');
	
	close OUTDOC_TXT;
	
	# Now save the document with metadata and text structure to docmets.xml
	
	my $doc_mets_file = &util::filename_cat ($working_dir, "docmets.xml");

	my $doc_title = $doc_obj->get_metadata_element($top_section,"dc.Title");
	if (!defined $doc_title) {
	    $doc_title = $doc_obj->get_metadata_element($top_section,"Title");
	}

	if (!open(OUTDOC_METS,">$doc_mets_file")){
	    print $outhandle "docsave::process could not write to file $doc_mets_file\n";
	    return;
	}
	
	my $saveas_version = $self->{'saveas_version'};
	$self->output_mets_xml_header('docsave::OUTDOC_METS', $OID, $doc_title);
	$doc_obj->output_mets_section('docsave::OUTDOC_METS',$top_section,$saveas_version,$working_dir);
	$self->output_mets_xml_footer('docsave::OUTDOC_METS');
	
	close OUTDOC_METS;	
    } 
    elsif ($save_as eq "DSpace") {

	# Generate dublin_core.xml file
	my $doc_dc_file = &util::filename_cat ($working_dir, "dublin_core.xml");
	
	if (!open(OUTDOC_DC,">$doc_dc_file")){
	    print $outhandle "docsave::process could not write dublin core to file $doc_dc_file\n";
	    return;
	}   
	
	my $saveas_version = $self->{'saveas_version'};

	$self->output_dc_xml_header('docsave::OUTDOC_DC', $OID);
	$doc_obj->output_dc_section('docsave::OUTDOC_DC',$top_section);
	$self->output_dc_xml_footer('docsave::OUTDOC_DC');
	
	close OUTDOC_DC;
    } else { # save_as isn't one of the recognised types
	print $outhandle "docsave::process unrecognised saveas type, $save_as\n";
	return;
    }


    my $short_doc_file;

    if ($save_as eq "GA") {
	$short_doc_file = util::filename_cat ($doc_dir, "doc.xml");
    } elsif ($save_as eq "METS") {
	$short_doc_file = &util::filename_cat ($doc_dir, "docmets.xml");
    } elsif ($save_as eq "DSpace") {
	$short_doc_file=&util::filename_cat ($doc_dir, "dublin_core.xml");
    } else {
	return;
    }

    #save for later (for close_file_output())
    $self->{'short_doc_file'} = $short_doc_file;	
 
    if ($self->{'gzip'}) {
	my $doc_file = $self->{'gs_filename'};
	`gzip $doc_file`;
	$doc_file .= ".gz";
	$short_doc_file .= ".gz";
	if (!-e $doc_file) {
	    print $outhandle "error while gzipping: $doc_file doesn't exist\n";
	    return 0;
	}
    }

    # do the sortmeta thing
    my ($metadata);	
    if (defined ($self->{'sortmeta'})) {
	$metadata = $doc_obj->get_metadata_element($top_section,$self->{'sortmeta'});
    }
    if (defined ($metadata) && $metadata) {
	# do remove prefix/suffix
	if (defined($self->{'removeprefix'})) {
	    $metadata =~ s/^$self->{'removeprefix'}//;
	}
	if (defined($self->{'removesuffix'})) {
	    $metadata =~ s/$self->{'removesuffix'}$//;
	}
	$metadata = &sorttools::format_metadata_for_sorting($self->{'sortmeta'}, $metadata, $doc_obj);
    }

    # store reference in the output_info
    $output_info->add_info($OID, $short_doc_file, undef, $metadata);
}

      
sub group_process {
    my $self = shift (@_);
    my ($doc_obj) = @_;
    
    my $outhandle = $self->{'outhandle'};

    my $OID = $doc_obj->get_OID();
    $OID = "NULL" unless defined $OID;

    my $groupsize = $self->{'groupsize'};
    my $gs_count = $self->{'gs_count'};
    my $open_new_file = (($gs_count % $groupsize)==0);

    # opening a new file, or document has assoicated files => directory needed
    if (($open_new_file) || (scalar(@{$doc_obj->get_assoc_files()})>0)) {

	# get document's directory
	my $doc_dir = $self->get_doc_dir ($OID, $doc_obj->get_source_filename());

	# copy all the associated files, add this information as metadata
	# to the document
	$self->process_assoc_files ($doc_obj, $doc_dir);


	if ($open_new_file) {
	    # only if opening new file
	    my $output_dir = $self->getoutputdir();
	    my $doc_file 
		= &util::filename_cat ($output_dir, $doc_dir, "doc.xml");
	    my $short_doc_file = &util::filename_cat ($doc_dir, "doc.xml");
	    
	    if ($gs_count>0)
	    {
		return if (!$self->close_file_output());
	    }
	    
	    if (!open (OUTDOC, ">$doc_file")) {
		print $outhandle "docsave::group_process could not write to file $doc_file\n";
		return;
	    }
	    $self->{'gs_filename'} = $doc_file;
	    $self->{'gs_short_filename'} = $short_doc_file;
	    $self->{'gs_OID'} = $OID;

	    $self->output_xml_header('docsave::OUTDOC');
	}
    }

    # save this document
    $doc_obj->output_section('docsave::OUTDOC', $doc_obj->get_top_section());

    $self->{'gs_count'}++;
}

sub get_doc_dir {
    my $self = shift (@_);
    my ($OID, $source_filename) = @_;

    my $service = $self-> {'service'};

    my $working_dir  = $self->getoutputdir();
    my $working_info = $self->getoutputinfo();
    return if (!defined $working_info);

    my $doc_info = $working_info->get_info($OID);
    my $doc_dir = '';

    if (defined $doc_info && scalar(@$doc_info) >= 1) {
	# this OID already has an assigned directory, use the
	# same one.
	$doc_dir = $doc_info->[0];
	$doc_dir =~ s/\/?((doc(mets)?)|(dublin_core))\.xml(\.gz)?$//;
    } elsif ($self->{'keepimportstructure'}) {
	$source_filename = &File::Basename::dirname($source_filename);
	$source_filename =~ s/[\\\/]+/\//g;
	$source_filename =~ s/\/$//;
 
	
	#print STDERR "Source filename: $source_filename; \nImport dir:",$ENV{'GSDLIMPORTDIR'}, "\n";
	$doc_dir = substr($source_filename, length($ENV{'GSDLIMPORTDIR'}) + 1);

    }
    if ($doc_dir eq "") {
	# have to get a new document directory

	if (($service eq "import") || ($service eq "unbuild")) {
	    my $doc_dir_rest = $OID;
	    my $doc_dir_num = 0;

	    do {
		$doc_dir .= "/" if $doc_dir_num > 0;
		if ($doc_dir_rest =~ s/^(.{1,8})//) {
		    $doc_dir .= $1;
		    $doc_dir_num++;
		}
	    } while ($doc_dir_rest ne "" && 
		     ((-d &util::filename_cat ($working_dir, "$doc_dir.dir")) || 
		      ($working_info->size() >= 1024 && $doc_dir_num < 2)));
	}
	else {
	    # Export formats such as DSpace need the directory structure to
	    # be flat.  This is simple to arrange (set 'doc_dir' to be the
	    # documents OID) but breaks Windows 3.1 file system compliance.
	    # Such a loss is not a big thing in this situation as such
	    # systems don't run on Windows 3.1 anyway.

	    $doc_dir = $OID;
	}


	$doc_dir .= ".dir";
	&util::mk_all_dir (&util::filename_cat ($working_dir, $doc_dir));
    }
    return $doc_dir;
}

sub process_assoc_files {
    my $self = shift (@_);
    my ($doc_obj, $doc_dir, $handle) = @_;

    my $outhandle = $self->{'outhandle'};
    my $service = $self->{'service'};
    my $save_as = $self->{'saveas'};

    my $output_dir = $self->getoutputdir();
    return if (!defined $output_dir);

    my $working_dir = &util::filename_cat($output_dir, $doc_dir);

    my @assoc_files = ();
    my $filename;;

    my $source_filename = $doc_obj->get_source_filename();

    my $collect_dir = $ENV{'GSDLCOLLECTDIR'};

    if (defined $collect_dir) {
	my $dirsep_regexp = &util::get_os_dirsep();

	if ($collect_dir !~ /$dirsep_regexp$/) {
	    $collect_dir .= &util::get_dirsep(); # ensure there is a slash at the end
	}

	# This test is never going to fail on Windows -- is this a problem?
	if ($source_filename !~ /^$dirsep_regexp/) {
	    $source_filename = &util::filename_cat($collect_dir, $source_filename);
	}
    }


    if ($save_as eq "DSpace") {
	my ($tail_filename) = ($source_filename =~ m/\/([^\/\\]*)$/);

	print $handle "$tail_filename\n";

	$filename = &util::filename_cat($working_dir, $tail_filename);
	&util::hard_link ($source_filename, $filename);
    }
         
    # set the assocfile path (even if we have no assoc files - need this for lucene)
    $doc_obj->set_utf8_metadata_element ($doc_obj->get_top_section(),
					 "assocfilepath",
					 "$doc_dir");
    foreach my $assoc_file_rec (@{$doc_obj->get_assoc_files()}) {
	my ($dir, $afile) = $assoc_file_rec->[1] =~ /^(.*?)([^\/\\]+)$/;
	$dir = "" unless defined $dir;
	    
	
	my $real_filename = $assoc_file_rec->[0];
	# for some reasons the image associate file has / before the full path
	$real_filename =~ s/^\\(.*)/$1/i;
	if (-e $real_filename) {


	    if ($save_as eq "DSpace") {
		if ($real_filename =~ m/$source_filename$/) {
		    next;
		}
		else {
		    my $bundle = "bundle:ORIGINAL";

		    if ($afile =~ m/^thumbnail\./) {
			$bundle = "bundle:THUMBNAIL";
		    }

		    # Store the associated file to the "contents" file
		    print $handle "$assoc_file_rec->[1]\t$bundle\n";
		}
	    }

	    $filename = &util::filename_cat($working_dir, $afile);


	    &util::hard_link ($real_filename, $filename);
	    
	    $doc_obj->add_utf8_metadata ($doc_obj->get_top_section(),
					 "gsdlassocfile",
					 "$afile:$assoc_file_rec->[2]:$dir");
	} elsif ($self->{'verbosity'} > 2) {
	    print $outhandle "docsave::process couldn't copy the associated file " .
		"$real_filename to $afile\n";
	}
    }
}
    

sub close_file_output
{
    my ($self) = @_;
    my $service =$self->{'service'};

    # make sure that the handle has been opened - it won't be if we failed
    # to import any documents...
    if (defined(fileno(docsave::OUTDOC))) {
	$self->output_xml_footer('docsave::OUTDOC');    
	close OUTDOC;
    }

    my $OID = $self->{'gs_OID'};
    my $short_doc_file;
    # can we use 'short_doc_file' for GA too?
    if (exists($self->{'saveas'}) && $self->{'saveas'} eq "METS") {
	$short_doc_file=$self->{'short_doc_file'};
    } elsif ($self->{'saveas'} eq "GA") { # "GA"
	$short_doc_file=$self->{'gs_short_filename'};
    } else { # "DSpace"
    }
    
    if ($self->{'gzip'}) {
	my $doc_file = $self->{'gs_filename'};
	`gzip $doc_file`;
	$doc_file .= ".gz";
	$short_doc_file .= ".gz";
	if (!-e $doc_file) {
	    my $outhandle = $self->{'outhandle'};
	    print $outhandle "error while gzipping: $doc_file doesn't exist\n";
	    return 0;
	}
    }

    # store reference in output_info
    my $output_info = $self->getoutputinfo();
    return 0 if (!defined $output_info);
    $output_info->add_info($OID, $short_doc_file, undef, undef);

    return 1;
}

sub output_xml_header {
    my $self = shift (@_);
    my ($handle) = @_;

    print $handle '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . "\n";
   
    print $handle '<!DOCTYPE Archive SYSTEM "http://greenstone.org/dtd/Archive/1.0/Archive.dtd">' . "\n";
    print $handle "<Archive>\n";
}

sub output_xml_footer {
    my $self = shift (@_);
    my ($handle) = @_;

    print $handle "</Archive>\n";
}

sub output_txt_xml_header{
    my $self = shift (@_);
    my ($handle) = @_;
    print $handle '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . "\n";
    print $handle '<!DOCTYPE Archive SYSTEM "http://greenstone.org/dtd/Archive/1.0/Archive.dtd">' . "\n";
}

sub output_txt_xml_footer{
    my $self = shift(@_);
    my ($handle) = @_;
    # Nothing needs to be output at present
}

sub output_mets_xml_header(){
    my $self = shift(@_);
    my ($handle, $OID, $doc_title) = @_;

    my $version = $self->{'saveas_version'};

    my $extra_attr = "";
    if ($version eq "fedora") {	
	my $fnamespace = $ENV{'FEDORA_PID_NAMESPACE'};
	my $oid_namespace = (defined $fnamespace) ? $fnamespace : "test";

	$extra_attr = "OBJID=\"$oid_namespace:$OID\" TYPE=\"FedoraObject\" LABEL=\"$doc_title\"";
    }
    else {
	# Greenstone METS profile
	$extra_attr = "OBJID=\"$OID:2\"";
    }


    print $handle '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . "\n";
    print $handle '<mets:mets xmlns:mets="http://www.loc.gov/METS/"' . "\n";
    print $handle '           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' . "\n";
    print $handle '           xmlns:gsdl3="http://www.greenstone.org/namespace/gsdlmetadata/1.0/"' . "\n";
    print $handle '           xmlns:xlink="http://www.w3.org/TR/xlink"' ."\n";
    print $handle '           xsi:schemaLocation="http://www.loc.gov/METS/' . "\n";
    print $handle '           http://www.loc.gov/standards/mets/mets.xsd' . "\n";
    print $handle '           http://www.greenstone.org/namespace/gsdlmetadata/1.0/' . "\n";
    print $handle '           http://www.greenstone.org/namespace/gsdlmetadata/1.0/gsdl_metadata.xsd"' . "\n";
    print $handle "  $extra_attr>\n";

    if ($version eq "fedora") {
	print $handle '<mets:metsHdr RECORDSTATUS="A"/>'. "\n"; # A = active
    }

}

sub output_mets_xml_footer() {
    my $self = shift(@_);
    my ($handle) = @_;
    print $handle '</mets:mets>' . "\n";
}

sub output_dc_xml_header(){
    my $self = shift(@_);
    my ($handle, $OID) = @_;

    print $handle '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . "\n";
#    print $handle '<!DOCTYPE Archive SYSTEM "http://greenstone.org/dtd/Archive/1.0/Archive.dtd">'."\n";
    print $handle '<dublin_core>' . "\n";
}

sub output_dc_xml_footer() {
    my $self = shift(@_);
    my ($handle) = @_;
    print $handle '</dublin_core>' . "\n";
}
1;
