###########################################################################
#
# inexport.pm -- useful utilities to support import.pl and export.pl
# 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.
#
###########################################################################

package inexport;

use strict;

use File::Basename;

use util;
use GDBMUtils;


sub prime_doc_oid_count
{
    my ($archivedir) = @_;
    my $oid_count_filename = &util::filename_cat ($archivedir, "OIDcount");

    if (-e $oid_count_filename) {
	if (open(OIDIN,"<$oid_count_filename")) {
	    my $OIDcount = <OIDIN>;
	    chomp $OIDcount;	    
	    close(OIDIN);

	    $doc::OIDcount = $OIDcount;	    
	}
	else {
	    
	    print STDERR "Warning: unable to read document OID count from $oid_count_filename\n";
	    print STDERR "Setting value to 0\n";
	}
    }
    
}

sub store_doc_oid_count
{
    # Use the file "OIDcount" in the archives directory to record
    # what value doc.pm got up to

    my ($archivedir) = @_;
    my $oid_count_filename = &util::filename_cat ($archivedir, "OIDcount");


    if (open(OIDOUT,">$oid_count_filename")) {
	print OIDOUT $doc::OIDcount, "\n";
	    
	close(OIDOUT);
    }
    else {
	print STDERR "Warning: unable to store document OID count\n";
    }
}



sub new_vs_old_import_diff
{
    my ($archive_info,$block_hash,$importdir) = @_;

    # First convert all files to absolute form
    # This is to support the situation where the import folder is not
    # the default
    
    my $prev_all_files = $archive_info->{'prev_import_filelist'};
    my $full_prev_all_files = {};

    foreach my $prev_file (keys %$prev_all_files) {

	if (!&util::filename_is_absolute($prev_file)) {
	    my $full_prev_file = &util::filename_cat($ENV{'GSDLCOLLECTDIR'},$prev_file);
	    $full_prev_all_files->{$full_prev_file} = $prev_file;
	}
	else {
	    $full_prev_all_files->{$prev_file} = $prev_file;
	}
    }


    # Figure out which are the new files, existing files and so
    # by implication the files from the previous import that are not
    # there any more => mark them for deletion
    foreach my $curr_file (keys %{$block_hash->{'all_files'}}) {
	
	my $full_curr_file = $curr_file;

	# entry in 'all_files' is moved to either 'existing_files', 
	# 'deleted_files', or 'new_files'

	if (!&util::filename_is_absolute($curr_file)) {
	    # add in import dir to make absolute
	    $full_curr_file = &util::filename_cat($importdir,$curr_file);
	}

	if (defined $block_hash->{'file_blocks'}->{$full_curr_file}) {
	    # If in block list, we want to ignore it
	    delete $block_hash->{'all_files'}->{$curr_file};

	    if (defined $full_prev_all_files->{$full_curr_file}) {
		# also make sure it is gone from 'previous' list so
		# not mistaken for a file that needs to be deleted
		delete $full_prev_all_files->{$full_curr_file};
	    }
	    next;
	}

	# figure of if new file or not
	if (defined $full_prev_all_files->{$full_curr_file}) {
	    
	    # had it before
	    $block_hash->{'existing_files'}->{$full_curr_file} = 1;

	    # Now remove it, so by end of loop only the files
	    # that need deleting are left

	    delete $full_prev_all_files->{$full_curr_file};
    	}
	else {
	    $block_hash->{'new_files'}->{$full_curr_file} = 1;
	}
	
	delete $block_hash->{'all_files'}->{$curr_file};
    }

    # By this point full_prev_all_files contains the files
    # mentioned in archiveinf-src.db but are not in the 'import'
    # folder (or whatever was specified through -importdir ...)

    # This list can contain files that were created in the 'tmp' or
    # 'cache' areas (such as screen-size and thumbnail images).
    #
    # In building the final list of files to delete, we test to see if
    # it exists on the filesystem and if it does (unusual for a file
    # that's allegedly deleted!) , supress it from going into the final
    # list

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

    my @deleted_files = values %$full_prev_all_files;
    map { my $curr_file = $_;
	  my $full_curr_file = $curr_file;

	  if (!&util::filename_is_absolute($curr_file)) {
	      # add in import dir to make absolute

	      $full_curr_file = &util::filename_cat($collectdir,$curr_file);
	  }


	  if (!-e $full_curr_file) {
	      $block_hash->{'deleted_files'}->{$curr_file} = 1;
	  }
      } @deleted_files;
}


sub _mark_docs_for_deletion
{
    my ($archive_info,$deleted_files_ref,$archivedir,$verbosity,$mode_text) = @_;

    my $doc_db = "archiveinf-doc.gdb";
    my $src_db = "archiveinf-src.gdb";
    my $arcinfo_doc_filename = &util::filename_cat ($archivedir, $doc_db);
    my $arcinfo_src_filename = &util::filename_cat ($archivedir, $src_db);


    # record files marked for deletion in arcinfo
    foreach my $file (@$deleted_files_ref) {
	# use 'archiveinf-src' GDBM file to look up all the OIDs
	# this file is used in (note in most cases, it's just one OID)
	
	my $src_rec = GDBMUtils::gdbmRecordToHash($arcinfo_src_filename,$file);
	my $oids = $src_rec->{'oid'};
	foreach my $oid (@$oids) {

	    # Find out if it's an assoc file or main doc

	    my $doc_rec = GDBMUtils::gdbmRecordToHash($arcinfo_doc_filename,$oid);
	    if ($doc_rec->{'src-file'}->[0] eq $file) {
		# It's the main doc
		# => mark it for deletion
	
		if ($verbosity>1) {
		    print STDERR "$oid ($file) marked to be $mode_text on next buildcol.pl\n";
		}
		$archive_info->set_status_info($oid,"D");

		my $val = &GDBMUtils::gdbmDatabaseGet($arcinfo_doc_filename,$oid);
		my ($index_status) = ($val =~ m/^<index-status>(.*)$/m);
		if ($index_status ne "D") {
		    $val =~ s/^<index-status>(.*)$/<index-status>D/m;
		    &GDBMUtils::gdbmDatabaseSet($arcinfo_doc_filename,$oid,$val);
		}
	    }
	    else {
		# assoc file => mark it for re-indexing (safest thing to do)
		my $curr_status = $archive_info->get_status_info($oid);


		if (defined($curr_status) && (($curr_status ne "D") && ($curr_status ne "R"))) {
		    if ($verbosity > 1) {
			print STDERR "$oid marked for (potential) reindexing\n";
			print STDERR "  (because associated file $file deleted)\n";
		    }
		    $archive_info->set_status_info($oid,"R");

		    my $val = &GDBMUtils::gdbmDatabaseGet($arcinfo_doc_filename,$oid);
		    $val =~ s/^<index-status>(.*)$/<index-status>R/m;
		    &GDBMUtils::gdbmDatabaseSet($arcinfo_doc_filename,$oid,$val);
		}
	    }

	    GDBMUtils::gdbmDatabaseRemove($arcinfo_src_filename,$file);
	}
    }
}


sub mark_docs_for_deletion
{
    _mark_docs_for_deletion(@_,"deleted from index");
}


sub mark_docs_for_reindex
{
    my ($archive_info,$existing_files_ref,$archivedir,$verbosity) = @_;

    # Reindexing is accomplished by deleting the previously indexed
    # version of the document, and then allowing the new version to
    # be indexed (as would a new document be indexed). 
    # 
    # The first step (marking for deletion) is implemented by this routine.
    # 
    # By default in Greenstone a new version of an index will hash to
    # a new unique OID, and the above strategy of reindex=delete+add
    # works fine.  A special case arises when a persistent OID is 
    # allocated to a document (for instance through a metadata field),
    # and the second step to reindexing (see XXXX) detects this and
    # deals with it appropriately.

    my $doc_db = "archiveinf-doc.gdb";
    my $arcinfo_doc_filename = &util::filename_cat ($archivedir, $doc_db);


    my $archiveinf_timestamp = -M $arcinfo_doc_filename;

    my $reindex_files_ref = [];

    foreach my $existing_filename (@$existing_files_ref) {
	
	if (-M $existing_filename < $archiveinf_timestamp) {
	    # file is newer than last build
	    
	    my $existing_file = $existing_filename;
	    my $collectdir = &util::filename_cat($ENV{'GSDLCOLLECTDIR'});

	    $existing_file =~ s/^$collectdir(\\|\/)?//;
	    
###	    print STDERR "**** Deleting existing file: $existing_file\n";

	    push(@$reindex_files_ref,$existing_file);
	}

    }
    
    _mark_docs_for_deletion($archive_info,$reindex_files_ref,$archivedir,$verbosity, "reindex");

    return @$reindex_files_ref;
}



1;
