#!/usr/bin/perl -w

###########################################################################
#
# import.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.
#
###########################################################################


# This program will import a number of files into a particular collection

package import;

BEGIN {
    die "GSDLHOME not set\n" unless defined $ENV{'GSDLHOME'};
    die "GSDLOS not set\n" unless defined $ENV{'GSDLOS'};
    unshift (@INC, "$ENV{'GSDLHOME'}/perllib");
    unshift (@INC, "$ENV{'GSDLHOME'}/perllib/cpan");
    unshift (@INC, "$ENV{'GSDLHOME'}/perllib/plugins");
    unshift (@INC, "$ENV{'GSDLHOME'}/perllib/classify");
}

use arcinfo;
use colcfg;
use plugin;
use docprint;
use util;
use scriptutil;
use FileHandle;
use gsprintf 'gsprintf';
use printusage;
use parse2;

use strict;
no strict 'refs'; # allow filehandles to be variables and vice versa
no strict 'subs'; # allow barewords (eg STDERR) as function arguments

my $oidtype_list = 
    [ { 'name' => "hash",
        'desc' => "{import.OIDtype.hash}" },
      { 'name' => "incremental",
        'desc' => "{import.OIDtype.incremental}" },
      { 'name' => "assigned",
        'desc' => "{import.OIDtype.assigned}" },
      { 'name' => "dirname",
        'desc' => "{import.OIDtype.dirname}" } ];

#** define to use the original GA format or METS format
my $saveas_list = 
    [ { 'name' => "GA",
        'desc' => "{import.saveas.GA}" },
      { 'name' => "METS",
        'desc' => "{import.saveas.METS}" } ];


# Possible attributes for each argument
# name: The name of the argument
# desc: A description (or more likely a reference to a description) for this argument
# type: The type of control used to represent the argument. Options include: string, int, flag, regexp, metadata, metadatum, language, enum etc
# reqd: Is this argument required?
# hiddengli: Is this argument hidden in GLI?
# modegli: The lowest detail mode this argument is visible at in GLI

my $arguments = 
    [ { 'name' => "archivedir",
	'desc' => "{import.archivedir}",
	'type' => "string",
	'reqd' => "no",
        'hiddengli' => "yes" },
      { 'name' => "collectdir",
	'desc' => "{import.collectdir}",
	'type' => "string",
	# parsearg left "" as default
	#'deft' => &util::filename_cat ($ENV{'GSDLHOME'}, "collect"),
	'deft' => "",
	'reqd' => "no",
        'hiddengli' => "yes" },
      { 'name' => "debug",
	'desc' => "{import.debug}",
	'type' => "flag",
	'reqd' => "no",
        'hiddengli' => "yes" },
      { 'name' => "faillog",
	'desc' => "{import.faillog}",
	'type' => "string",
	# parsearg left "" as default
	#'deft' => &util::filename_cat("&lt;collectdir&gt;", "colname", "etc", "fail.log"),
	'deft' => "",
	'reqd' => "no",
        'modegli' => "4" },
      { 'name' => "groupsize",
	'desc' => "{import.groupsize}",
	'type' => "int",
	'deft' => "1",
	'reqd' => "no",
	'modegli' => "3" },
      { 'name' => "gzip",
	'desc' => "{import.gzip}",
	'type' => "flag",
	'reqd' => "no",
	'modegli' => "4" },
      { 'name' => "importdir",
	'desc' => "{import.importdir}",
	'type' => "string",
	'reqd' => "no",
        'hiddengli' => "yes" },
      { 'name' => "keepold",
	'desc' => "{import.keepold}",
	'type' => "flag",
	'reqd' => "no",
        'modegli' => "3" },
      { 'name' => "removeold",
	'desc' => "{import.removeold}",
	'type' => "flag",
	'reqd' => "no",
	'modegli' => "3" },
      { 'name' => "language",
	'desc' => "{scripts.language}",
	'type' => "string",
	'reqd' => "no",
	'modegli' => "4" },
      { 'name' => "maxdocs",
	'desc' => "{import.maxdocs}",
	'type' => "int",
	'reqd' => "no",
	# parsearg left "" as default
	#'deft' => "-1",
	'range' => "1,",
	'modegli' => "1" },
      { 'name' => "OIDtype",
	'desc' => "{import.OIDtype}",
	'type' => "enum",
	'list' => $oidtype_list,
	# parsearg left "" as default
	#'deft' => "hash",
	'reqd' => "no",
	'modegli' => "3" },
      { 'name' => "out",
	'desc' => "{import.out}",
	'type' => "string",
	'deft' => "STDERR",
	'reqd' => "no",
        'hiddengli' => "yes" },
      { 'name' => "saveas",
	'desc' => "{import.saveas}",
	'type' => "enum",
	'list' => $saveas_list,
	'deft' => "GA",
	'reqd' => "no",
	'modegli' => "3" },      
      { 'name' => "sortmeta",
	'desc' => "{import.sortmeta}",
#	'type' => "metadatum",
	'type' => "string",
	'reqd' => "no",
	'modegli' => "3" },
      { 'name' => "removeprefix",
	'desc' => "{BasClas.removeprefix}",
	'type' => "regexp",
	'deft' => "",
	'reqd' => "no", 
	'modegli' => "3" },
      { 'name' => "removesuffix",
	'desc' => "{BasClas.removesuffix}",
	'type' => "regexp",
	'deft' => "",
	'reqd' => "no",
	'modegli' => "3" }, 
      { 'name' => "statsfile",
	'desc' => "{import.statsfile}",
	'type' => "string",
	'deft' => "STDERR",
	'reqd' => "no",
        'hiddengli' => "yes" },
      { 'name' => "verbosity",
	'desc' => "{import.verbosity}",
	'type' => "int",
	'range' => "0,",
	# parsearg left "" as default
	#'deft' => "2",
	'reqd' => "no",
	'modegli' => "4" },
      { 'name' => "gli",
	'desc' => "",
	'type' => "flag",
	'reqd' => "no",
	'hiddengli' => "yes" },
      { 'name' => "xml",
	'desc' => "{scripts.xml}",
	'type' => "flag",
	'reqd' => "no",
	'hiddengli' => "yes" }];

my $options = { 'name' => "import.pl",
		'desc' => "{import.desc}",
		'args' => $arguments };


&main();

sub main {
    my ($verbosity, $importdir, $archivedir, $keepold, 
	$removeold, $saveas, $version,
	$gzip, $groupsize, $OIDtype, $debug, 
	$maxdocs, $collection, $configfilename, $collectcfg, 
	$pluginfo, $sortmeta, $removeprefix, $removesuffix, 
	$archive_info_filename, $statsfile,
	$archive_info, $processor, $out, $faillog, $collectdir, $gli, $language);

    my $xml = 0;

    my $service = "import";

    my $hashParsingResult = {};
    my $blnParseFailed = "false";
    # general options available to all plugins
    my $intArgLeftinAfterParsing = parse2::parse(\@ARGV,$arguments,$hashParsingResult,"allow_extra_options");
    # If there is more than one argument left after parsing, it mean user input too many arguments.
    if($intArgLeftinAfterParsing > 1)
    {
	&PrintUsage::print_txt_usage($options, "{import.params}");
	die "\n";
    }
    
    foreach my $strVariable (keys %$hashParsingResult)
    {
	eval "\$$strVariable = \$hashParsingResult->{\"\$strVariable\"}";
    }

    # If $language has been specified, load the appropriate resource bundle
    # (Otherwise, the default resource bundle will be loaded automatically)
    if ($language && $language =~ /\S/) {
	&gsprintf::load_language_specific_resource_bundle($language);
    }

    if ($xml) {
        &PrintUsage::print_xml_usage($options);
	print "\n";
	return;
    }

    if ($gli) { # the gli wants strings to be in UTF-8
	&gsprintf::output_strings_in_UTF8; 
    }

    my $close_out = 0;
    if ($out !~ /^(STDERR|STDOUT)$/i) {
	open (OUT, ">$out") ||
	    (&gsprintf(STDERR, "{common.cannot_open_output_file}\n", $out) && die);
	$out = 'import::OUT';
	$close_out = 1;
    }
    $out->autoflush(1);

    # get and check the collection name
    if (($collection = &util::use_collection(@ARGV, $collectdir)) eq "") {
	&PrintUsage::print_txt_usage($options, "{import.params}");
	die "\n";
    }

    if ($faillog eq "") {
	$faillog = &util::filename_cat($ENV{'GSDLCOLLECTDIR'}, "etc", "fail.log");
    }
    open (FAILLOG, ">$faillog") ||
	(&gsprintf(STDERR, "{import.cannot_open_fail_log}\n", $faillog) && die);

    
    my $faillogname = $faillog;
    $faillog = 'import::FAILLOG';
    $faillog->autoflush(1);

    # check sortmeta
    $sortmeta = undef unless defined $sortmeta && $sortmeta =~ /\S/;
    if (defined $sortmeta && $groupsize > 1) {
	&gsprintf($out, "{import.cannot_sort}\n\n");
	$sortmeta = undef;
    }
    # dynamically load 'docsave' module so it can pick up on a collection
    # specific docsave.pm is specified.

    unshift (@INC, "$ENV{'GSDLCOLLECTDIR'}/perllib");
    require docsave;

    # get the list of plugins for this collection and set any options that
    # were specified in the collect.cfg (all import.pl options except
    # -collectdir, -out and -faillog may be specified in the collect.cfg (these
    # options must be known before we read the collect.cfg))
    my $plugins = [];
    my @global_opts = ();
    
    $configfilename = &util::filename_cat ($ENV{'GSDLCOLLECTDIR'}, "etc", "collect.cfg");
    if (!-e $configfilename) {
	(&gsprintf($out, "{common.cannot_find_cfg_file}\n", $configfilename) && die);
    }
    
    $collectcfg = &colcfg::read_collect_cfg ($configfilename);
    if (defined $collectcfg->{'plugin'}) {
	$plugins = $collectcfg->{'plugin'};
    }

    if ($verbosity !~ /\d+/) {
	if (defined $collectcfg->{'verbosity'} && $collectcfg->{'verbosity'} =~ /\d+/) {
	    $verbosity = $collectcfg->{'verbosity'};
	} else {
	    $verbosity = 2; # the default
	}
    }
    if (defined $collectcfg->{'importdir'} && $importdir eq "") {
	$importdir = $collectcfg->{'importdir'};
    }
    if (defined $collectcfg->{'archivedir'} && $archivedir eq "") {
	$archivedir = $collectcfg->{'archivedir'};
    }

    if (defined $collectcfg->{'gzip'} && !$gzip) {
	if ($collectcfg->{'gzip'} =~ /^true$/i) {
	    $gzip = 1;
	}
    }
    if ($maxdocs !~ /\-?\d+/) {
	if (defined $collectcfg->{'maxdocs'} && $collectcfg->{'maxdocs'} =~ /\-?\d+/) {
	    $maxdocs = $collectcfg->{'maxdocs'};
	} else {
	    $maxdocs = -1; # the default
	}
    }
    if ($groupsize == 1) {
	if (defined $collectcfg->{'groupsize'} && $collectcfg->{'groupsize'} =~ /\d+/) {
	    $groupsize = $collectcfg->{'groupsize'};
	}
    }
    if ($OIDtype !~ /^(hash|incremental|assigned|dirname)$/) {
	if (defined $collectcfg->{'OIDtype'} && $collectcfg->{'OIDtype'} =~ /^(hash|incremental|assigned|dirname)$/) {
	    $OIDtype = $collectcfg->{'OIDtype'};
	} else {
	    $OIDtype = "hash"; # the default
	}
    }
    if ($saveas !~ /^(GA|METS)$/) {
	if (defined $collectcfg->{'saveas'} && $collectcfg->{'saveas'} =~ /^(GA|METS)$/) {
	    $saveas = $collectcfg->{'saveas'};
	} else {
	    $saveas ="GA";
	}
    }
    if (defined $collectcfg->{'sortmeta'} && (!defined $sortmeta || $sortmeta eq "")) {
	$sortmeta = $collectcfg->{'sortmeta'};
    }
    
    if (defined $collectcfg->{'removeprefix'} && $removeprefix eq "") {
	$removeprefix = $collectcfg->{'removeprefix'};
    }
    
    if (defined $collectcfg->{'removesuffix'} && $removesuffix eq "") {
	$removesuffix = $collectcfg->{'removesuffix'};
    }
    if (defined $collectcfg->{'debug'} && $collectcfg->{'debug'} =~ /^true$/i) {
	$debug = 1;
    }
    if (defined $collectcfg->{'gli'} && $collectcfg->{'gli'} =~ /^true$/i) {
	$gli = 1;
    }
    
    
    # global plugin stuff
    if (defined $collectcfg->{'separate_cjk'} && $collectcfg->{'separate_cjk'} =~ /^true$/i) {
	push @global_opts, "-separate_cjk";
    }
    
    # check keepold and removeold
    ($removeold, $keepold) = &scriptutil::check_removeold_and_keepold($removeold, $keepold, "archives", $collectcfg);
 
    $gli = 0 unless defined $gli;

    print STDERR "<Import>\n" if $gli;
    
    # fill in the default import and archives directories if none
    # were supplied, turn all \ into / and remove trailing /
    $importdir = &util::filename_cat ($ENV{'GSDLCOLLECTDIR'}, "import") if $importdir eq "";
    $importdir =~ s/[\\\/]+/\//g;
    $importdir =~ s/\/$//;
    $archivedir = &util::filename_cat ($ENV{'GSDLCOLLECTDIR'}, "archives") if $archivedir eq "";
    $archivedir =~ s/[\\\/]+/\//g;
    $archivedir =~ s/\/$//;

    # load all the plugins
    $pluginfo = &plugin::load_plugins ($plugins, $verbosity, $out, $faillog, \@global_opts);
    if (scalar(@$pluginfo) == 0) {
	&gsprintf($out, "{import.no_plugins_loaded}\n");
	die "\n";
    }

    # remove the old contents of the archives directory (and tmp directory) if needed
    if ($removeold) {
	if (-e $archivedir) {
	    &gsprintf($out, "{import.removing_archives}\n");
	    &util::rm_r ($archivedir);
	}
	my $tmpdir = &util::filename_cat ($ENV{'GSDLCOLLECTDIR'}, "tmp");
	$tmpdir =~ s/[\\\/]+/\//g;
	$tmpdir =~ s/\/$//;
	if (-e $tmpdir) {
	    &gsprintf($out, "{import.removing_tmpdir}\n");
	    &util::rm_r ($tmpdir);
	}
    }

    # read the archive information file
    if (!$debug) {
	$archive_info_filename = &util::filename_cat ($archivedir, "archives.inf");
	$archive_info = new arcinfo ();
	$archive_info->load_info ($archive_info_filename);

	# create a docsave object to process the documents
	$processor = new docsave ($collection, $archive_info, $verbosity, $gzip, $groupsize, $out, $service, $saveas);
	$processor->setoutputdir ($archivedir);
	$processor->set_sortmeta ($sortmeta, $removeprefix, $removesuffix) if defined $sortmeta;
	$processor->set_OIDtype ($OIDtype);
	$processor->set_saveas ($saveas);
	$processor->set_saveas_version ($version);

    } else {
	$processor = new docprint ();
    }

    &plugin::begin($pluginfo, $importdir, $processor, $maxdocs);

    # process the import directory
    &plugin::read ($pluginfo, $importdir, "", {}, $processor, $maxdocs, 0, $gli);
    
    &plugin::end($pluginfo, $processor);

    &plugin::deinit($pluginfo, $processor);

    # write out the archive information file
    if (!$debug) {
	$processor->close_file_output() if $groupsize > 1;
	$archive_info->save_info($archive_info_filename);
    }
    
    # write out import stats
    my $close_stats = 0;
    if ($statsfile !~ /^(STDERR|STDOUT)$/i) {
	if (open (STATS, ">$statsfile")) {
	    $statsfile = 'import::STATS';
	    $close_stats = 1;
	} else {
	    &gsprintf($out, "{import.cannot_open_stats_file}", $statsfile);
	    &gsprintf($out, "{import.stats_backup}\n");
	    $statsfile = 'STDERR';
	}
    }

    &gsprintf($out, "\n");
    &gsprintf($out, "*********************************************\n");
    &gsprintf($out, "{import.complete}\n");
    &gsprintf($out, "*********************************************\n");

    &plugin::write_stats($pluginfo, $statsfile, $faillogname, $gli);
    if ($close_stats) {
	close STATS;
    }

    close OUT if $close_out;
    close FAILLOG;
}
