#!/usr/bin/perl -w

###########################################################################
#
# build --
# A component of the Greenstone digital library software
# from the New Zealand Digital Library Project at the 
# University of Waikato, New Zealand.
#
# Copyright (C) 2000 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 perl script may be called directly or by running build.bat on
# windows (build.bat is in bin\windows)

# Note that this script has grown over time and now has many options for
# use when called from within the collector. If it appears to
# over-complicate things a little, that's why.

package build;

use FileHandle;
use File::Copy;

BEGIN {

    die "GSDLHOME not set - did you remember to source setup.bash (unix) or " .
	"run setup.bat (windows)?\n" unless defined $ENV{'GSDLHOME'};
    die "GSDLOS not set - did you remember to source setup.bash (unix) or " .
	"run setup.bat (windows)?\n" unless defined $ENV{'GSDLOS'};
    unshift (@INC, "$ENV{'GSDLHOME'}/perllib");

    STDOUT->autoflush(1);
    STDERR->autoflush(1);
}

use lib qq($ENV{'GSDLHOME'}/perllib/cpan);
use Mail::Sendmail;
use parsargv;
use util;
use cfgread;

# set up path - this allows for paths not to be supplied to system calls
# and overcomes problems when GSDLHOME contains spaces (double quoting
# the call doesn't work on win2k and probably other variants of winnt)
my $path_separator = ":";
$path_separator = ";" if $ENV{'GSDLOS'} =~ /^windows$/;
$ENV{'PATH'} = &util::filename_cat($ENV{'GSDLHOME'}, "bin", $ENV{'GSDLOS'}) .
    $path_separator . &util::filename_cat($ENV{'GSDLHOME'}, "bin", "script") .
    $path_separator . $ENV{'PATH'};

&parse_args (\@ARGV);

my ($collection) = @ARGV;

if (!defined $collection || $collection !~ /\w/) {
    print STDERR "You must specify a collection to build\n";
    &print_usage();
    die "\n";
}

if ($optionfile =~ /\w/) {
    open (OPTIONS, $optionfile) || die "Couldn't open $optionfile\n";
    my $line = [];
    my $options = [];
    while (defined ($line = &cfgread::read_cfg_line ('build::OPTIONS'))) {
	push (@$options, @$line);
    }
    close OPTIONS;
    &parse_args ($options);
}

if ($maxdocs == -1) {
    $maxdocs = "";
} else {
    $maxdocs = "-maxdocs $maxdocs";
}

my $cdir = $collectdir;
$cdir = &util::filename_cat ($ENV{'GSDLHOME'}, "collect") unless $collectdir =~ /\w/;
my $importdir = &util::filename_cat ($cdir, $collection, "import");
my $archivedir = &util::filename_cat ($cdir, $collection, "archives");
my $buildingdir = &util::filename_cat ($cdir, $collection, "building");
my $indexdir = &util::filename_cat ($cdir, $collection, "index");
my $bindir = &util::filename_cat ($ENV{'GSDLHOME'}, "bin");

my $use_out = 0;
my $outfile = $out;
if ($out !~ /^(STDERR|STDOUT)$/i) {
    open (OUT, ">$out") || die "Couldn't open output file $out\n";
    $out = "OUT";
    
    # delete any existing .final file
    &util::rm ("$outfile.final") if -e "$outfile.final";

    $use_out = 1;
}
$out->autoflush(1);

# delete any .kill file left laying around from a previously aborted build
if (-e &util::filename_cat ($cdir, $collection, ".kill")) {
    &util::rm (&util::filename_cat ($cdir, $collection, ".kill"));
}

# get maintainer email address from main.cfg
my $maintainer = "NULL";
my $main_cfg = &util::filename_cat ($ENV{'GSDLHOME'}, "etc", "main.cfg");
my $cfgdata = &cfgread::read_cfg_file ($main_cfg, "maintainer");
if (defined $cfgdata->{'maintainer'} && $cfgdata->{'maintainer'} =~ /\w/) {
    $maintainer = $cfgdata->{'maintainer'};
}
# if maintainer is "NULL" email_events should be disabled
if ($maintainer =~ /^NULL$/i) {
    $email_events = "";
}

&main();

close OUT if $use_out;

sub print_usage {
    print STDERR "\n";
    print STDERR "build: Builds a Greenstone collection (i.e. runs import.pl and buildcol.pl\n";
    print STDERR "       then copies the resulting indexes to the correct place).\n\n";
    print STDERR "  usage: $0 [options] collection-name\n\n";
    print STDERR "  options:\n";
    print STDERR "   -optionfile file        Get options from file, useful on systems where\n";
    print STDERR "                           long command lines may cause problems\n";
    print STDERR "   -append                 Add new files to existing collection\n";
    print STDERR "   -remove_archives        Remove archives directory after successfully\n";
    print STDERR "                           building the collection.\n";
    print STDERR "   -remove_import          Remove import directory after successfully\n";
    print STDERR "                           importing the collection.\n";
    print STDERR "   -buildtype build|import If 'build' attempt to build directly\n";
    print STDERR "                           from archives directory (bypassing import\n";
    print STDERR "                           stage). Defaults to 'import'\n";
    print STDERR "   -maxdocs number         Maximum number of documents to build\n";
    print STDERR "   -download directory     Directory (or file) to get import documents from.\n";
    print STDERR "                           There may be multiple download directories and they\n";
    print STDERR "                           may be of type http://, ftp://, or file://\n";
    print STDERR "                           Note that any existing import directory will be\n";
    print STDERR "                           deleted to make way for the downloaded data if\n";
    print STDERR "                           a -download option is supplied\n";
    print STDERR "   -collectdir directory   Collection directory (defaults to " .
	&util::filename_cat ($ENV{'GSDLHOME'}, "collect") . ")\n";
    print STDERR "   -dontinstall            Only applicable if -collectdir is set to something\n";
    print STDERR "                           other than the default. -dontinstall will suppress the\n";
    print STDERR "                           default behaviour which is to install the collection to\n";
    print STDERR "                           the gsdl/collect directory once it has been built.\n";
    print STDERR "   -save_archives          Create a copy of the existing archives directory called\n";
    print STDERR "                           archives.org\n";
    print STDERR "   -out                    Filename or handle to print output status to.\n";
    print STDERR "                           The default is STDERR\n";
    print STDERR "   -log_events             Log important events (collection built successfully etc.)\n";
    print STDERR "                           to event_log_file\n";
    print STDERR "   -event_log_file file    File to append important events to (defaults to\n";
    print STDERR "                           " . &util::filename_cat ($ENV{'GSDLHOME'}, "etc", "events.txt") . "\n";
    print STDERR "   -email_events addr      Comma separated list of email addresses to mail details\n";
    print STDERR "                           of important collection building events\n";
    print STDERR "   -mail_server server     The outgoing (SMTP) mail server to be used by email_events.\n";
    print STDERR "                           email_events will be disabled if mail_server isn't set\n";
    print STDERR "   -event_header file      File containing a header to go on any event messages. If not\n";
    print STDERR "                           specified build will create a generic header\n\n";
}

sub main {

    if ($save_archives && -d $archivedir) {
	print $out "caching original archives to ${archivedir}.org\n";
	&util::cp_r ($archivedir, "${archivedir}.org");
    }

    # do the download thing if we have any -download options
    if (scalar (@download)) {
	# remove any existing import data
	if (&has_content ($importdir)) {
	    print $out "build: WARNING: removing contents of $importdir\n";
	    &util::rm_r ($importdir);
	}
	
	foreach $download_dir (@download) {

	    # remove any leading or trailing whitespace from filenames (just in case)
	    $download_dir =~ s/^\s+//;
	    $download_dir =~ s/\s+$//;
	    
	    if ($download_dir =~ /^(http|ftp):\/\//) {
		# use wget to mirror http or ftp urls
		# options used are:
		#  -P = the directory to download documents to
		#  -np = don't ascend to parent directories. this means that only documents
		#        that live in the same directory or below on the same server as
		#        the given url will be downloaded
		#  -nv = not too verbose
		#  -r = recursively mirror
		#  -N = use time-stamping to see if an up-to-date local copy of each 
		#       file already exists. this may be useful if wget fails and 
		#       is restarted
		#  -l inf = infinite recursion depth
		#  -R "*\?*" = don't download cgi based urls
		#  -o = the output file to write download status to (only used if the -out
		#       option was given to build)

		my $download_cmd = "perl -S gsWget.pl -P \"$importdir\" -np -nv";
		$download_cmd .= " -r -N -l inf -R \"*\\?*\"";
		$download_cmd .= " -o \"$outfile.download\"" if $use_out;
		$download_cmd .= " \"$download_dir\"";
		system ($download_cmd);

		# note that wget obeys the robot rules. this means that it will have
		# downloaded a robots.txt file if one was present. since it's unlikely 
		# anyone really wants to include it in a collection we'll delete it.
		# robots.txt shouldn't be more than two directories deep (I think it will 
		# always be exactly two deep but will look for it in the top directory too)
		# so that's as far as we'll go looking for it.
		if (opendir (DIR, $importdir)) {
		    my @files = readdir DIR;
		    closedir DIR;
		    foreach my $file (@files) {
			next if $file =~ /^\.\.?$/;
			if ($file =~ /^robots.txt$/i) {
			    &util::rm (&util::filename_cat ($importdir, $file));
			    last;
			} else {
			    $file = &util::filename_cat ($importdir, $file);
			    if (-d $file) {
				if (opendir (DIR, $file)) {
				    my @files2 = readdir DIR;
				    closedir DIR;
				    foreach my $file2 (@files2) {
					if ($file2 =~ /^robots.txt$/i) {
					    &util::rm (&util::filename_cat ($file, $file2));
					    last;
					}
				    }
				}
			    }
			}
		    }
		}

		# if using output directory append the file download output to it
		&append_file ($out, "$outfile.download");
		
	    } else {
		# we assume anything not beginning with http:// or ftp://
		# is a file or directory on the local file system.
		$download_dir =~ s/^file:(\/\/)?//;
		$download_dir =~ s/^\s+//; # may be whitespace between "file://" and the rest
		
		if (-e $download_dir) {
		    # copy download_dir and all it contains to the import directory
		    my $download_cmd = "perl -S filecopy.pl";
		    $download_cmd .= " -collectdir \"$collectdir\"" if $collectdir =~ /\w/;
		    $download_cmd .= " -out \"$outfile.download\"" if $use_out;
		    $download_cmd .= " \"" . $download_dir . "\" " . $collection;
		    system ($download_cmd);
		    # if using output directory append the file download output to it
		    &append_file ($out, "$outfile.download");
		} else {
		    print $out "WARNING: '$download_dir' does not exist\n";
		}
	    }
	}
    }

    if (-e &util::filename_cat ($archivedir, "archives.inf")) {
	if (&has_content ($importdir)) {
	    if ($buildtype eq "build") {
		&gsdl_build();
	    } else {
		&gsdl_import();
		&gsdl_build();
	    }
	} else {
	    # there are archives but no import, build directly from archives
	    print $out "build: no import material was found, building directly\n";
	    print $out "       from archives\n";
	    &gsdl_build();
	}
    } else {
	if (&has_content ($importdir)) {
	    if ($buildtype eq "build") {
		print $out "build: can't build directly from archives as no\n";
		print $out "       imported archives exist (did you forget to\n";
		print $out "       move the contents of $collection/import to\n";
		print $out "       collection/archives?)\n";
	    }
	    &gsdl_import();
	    &gsdl_build();
	} else {
	    # no import or archives
	    my $msg = "build: ERROR: The $collection collection has no import or archives data.\n";
	    print $out $msg;
	    &log_event ($msg);
	    &final_out (1) if $use_out;
	    die "\n";
	}
    }

    if ($collectdir ne "" && !$dontinstall) {
	my $install_collectdir = &util::filename_cat ($ENV{'GSDLHOME'}, "collect");
	if (!&util::filenames_equal ($collectdir, $install_collectdir)) {
	    
	    # install collection to gsdl/collect
	    print $out "installing the $collection collection\n";
	    my $newdir = &util::filename_cat ($install_collectdir, $collection);
	    my $olddir = &util::filename_cat ($collectdir, $collection);
	    if (-d $newdir) {
		my $msg = "build: Could not install collection as $newdir\n" .
		    "       already exists. Collection will remain at\n$olddir\n";

		print $out $msg;
		&log_event ($msg);
		&final_out (4) if $use_out;
		die "\n";
	    }
	    if (!&File::Copy::move ($olddir, $newdir)) {
		my $msg = "build: Failed to install collection to $newdir\n" .
		    "       Collection will remain at $olddir\n";
		print $out $msg;
		&log_event ($msg);
		&final_out (5) if $use_out;
		die "\n";
	    }
	}
    }

    &log_event ("The $collection collection was built successfully\n");
    &final_out (0) if $use_out;
}

sub gsdl_import {

    print $out "importing the $collection collection\n\n";

    my $import_cmd = "perl -S import.pl";
    $import_cmd .= " -out \"$outfile.import\"" if $use_out;
    $import_cmd .= " -removeold" unless $append;
    $import_cmd .= " -collectdir \"$collectdir\"" if $collectdir =~ /\w/;
    $import_cmd .= " $maxdocs $collection";
    system ($import_cmd);
    # if using output directory append the import output to it
    &append_file ($out, "$outfile.import");

    if (-e &util::filename_cat ($archivedir, "archives.inf")) {
	print $out "$collection collection imported successfully\n\n";
	if ($remove_import) {
	    print $out "removing import directory ($importdir)\n";
	    &util::rm_r ($importdir);
	}
    } else {
	my $msg = "build: ERROR: import.pl failed\n";
	print $out "\n$msg";
	&log_event ($msg);
	&final_out (2) if $use_out;
	die "\n";
    }
}

sub gsdl_build {

    print $out "building the $collection collection\n\n";

    my $build_cmd = "perl -S buildcol.pl";
    $build_cmd .= " -out \"$outfile.build\"" if $use_out;
    $build_cmd .= " -collectdir \"$collectdir\"" if $collectdir =~ /\w/;
    $build_cmd .= " $maxdocs $collection";
    system ($build_cmd);
    # if using output directory append the buildcol output to it
    &append_file ($out, "$outfile.build");

    if (-e &util::filename_cat ($buildingdir, "text", "$collection.ldb") ||
	-e &util::filename_cat ($buildingdir, "text", "$collection.bdb")) {
	print $out "$collection collection built successfully\n\n";
	if ($remove_archives) {
	    print $out "removing archives directory ($archivedir)\n";
	    &util::rm_r ($archivedir);
	}
    } else {
	my $msg = "build: ERROR: buildcol.pl failed\n";
	print $out "\n$msg";
	&log_event ($msg);
	&final_out (3) if $use_out;
	die "\n";
    }

    # replace old indexes with new ones
    if (&has_content ($indexdir)) {
	print $out "removing old indexes\n";
	&util::rm_r ($indexdir);
    }
    rmdir ($indexdir) if -d $indexdir;
    &File::Copy::move ($buildingdir, $indexdir);

    # remove the cached arhives
    if ($save_archives && -d "${archivedir}.org") {
	&util::rm_r ("${archivedir}.org");
    }
}

sub has_content {
    my ($dir) = @_;

    if (!-d $dir) {return 0;}

    opendir (DIR, $dir) || return 0;
    my @files = readdir DIR;
    close DIR;
    
    foreach my $file (@files) {
	if ($file !~ /^\.{1,2}$/) {
	    return 1;
	}
    }
    return 0;
}

sub append_file {
    my ($handle, $file) = @_;

    open (FILE, $file) || return;
    undef $/;
    print $handle <FILE>;
    $/ = "\n";
    close FILE;
    &util::rm ($file);
}

# creates a file called $outfile.final (should only be called if -out option
# is used and isn't STDERR or STDOUT) and writes an output code to it.
# An output code of 0 specifies that there was no error
sub final_out {
    my ($exit_code) = @_;

    if (open (FINAL, ">$outfile.final")) {
	print FINAL $exit_code;
	close FINAL;
    }
}

sub log_event {
    my ($msg) = @_;

    return unless ($log_events || $email_events);

    # get the event header
    my $eheader = "[Build Event]\n";
    $eheader .= "Date: " . scalar localtime() . "\n";
    if ($event_header ne "" && open (HEADER, $event_header)) {
	undef $/;
	$eheader .= <HEADER>;
	$/ = "\n";
	close HEADER;
    } else {
	$eheader .= "Collection: $collection\n";
	$eheader .= "GSDLHOME: $ENV{'GSDLHOME'}\n";
	$eheader .= "Build Location: $collectdir\n";
    }
    
    if ($log_events) {
	my $fail = 0;
	# append the event to the event log file
	if ($event_log_file eq "" || !open (LOG, ">>$event_log_file")) {
	    # log file defaults to $GSDLHOME/etc/events.txt
	    $event_log_file = &util::filename_cat ($ENV{'GSDLHOME'}, "etc", "events.txt");
	    if (!open (LOG, ">>$event_log_file")) {
		print $out "build: ERROR: Couldn't open event log file $event_log_file\n";
		$fail = 1;
	    }
	}
	if (!$fail) {
	    print LOG $eheader;
	    print LOG $msg;
	    print LOG "\n";
	    close LOG;
	}
    }
    
    if ($email_events) {
	# if mail_server isn't set email_events does nothing
	if ($mail_server eq "") {
	    print $out "build: WARNING: mail_server was not set - email_events option was ignored\n";
	    return;
	}
	
	my %mail = ('SMTP' => $mail_server, 
		    'To' => $email_events,
		    'From' => $maintainer,
		    'Subject' => 'Greenstone Build Event'
		    );
	$mail{'Message'} = $eheader . $msg;
	
	if (!sendmail %mail) {
	    print $out "build: ERROR sending mail to $email_events\n";
	    print $out "'$Mail::Sendmail::error'\n";
	}
    }
}


sub parse_args {
    my ($argref) = @_;

    if (!parsargv::parse($argref, 
			 'optionfile/.*/', \$optionfile,
			 'append', \$append,
			 'remove_archives', \$remove_archives,
			 'remove_import', \$remove_import,
			 'buildtype/^(build|import)$/import', \$buildtype,
			 'maxdocs/^\-?\d+/-1', \$maxdocs,
			 'download/.+', \@download,
			 'collectdir/.*/', \$collectdir,
			 'dontinstall', \$dontinstall,
			 'save_archives', \$save_archives,
			 'out/.*/STDERR', \$out,
			 'log_events', \$log_events,
			 'event_log_file/.*/', \$event_log_file,
			 'email_events/.*/', \$email_events,
			 'mail_server/.*/', \$mail_server,
			 'event_header/.*/', \$event_header)) {
	
	&print_usage();
	die "\n";
    }
}
