#!/usr/bin/perl -w


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


# create_distributions.pl creates the following distributions from the gsdl
# directory pointed to by $GSDLHOME (although it uses the main CVS
# repository to get the latest source code distribution).

# Windows distribution - gsdl-x.xx-win32.exe
# Creates directory structure for this - use Installshield to create installer

# Unix distribution - gsdl-x.xx-unix.tgz

# Source distribution - gsdl-x.xx.tgz

# cd-rom distribution = gsdl-x.xx-cdrom.tgz
# Creates directory structure - use Installshield to create media
# for writing to cd-rom

# all collections in $GSDLHOME/collect (except modelcol and those
# explicitly ignored by -ignorecol options):
#  pre-built (collname-prebuilt) .tgz .zip
#  unbuilt (collname) .tgz .zip


#    creates ChangeLog using `cvs2cl.pl -P -F trunk -r -S -l "-d'date<tomorrow'"
#    where date of last distribution is read from the last line of 
#    $GSDLHOME/DistDates or from -ChangeLogDate command line option
#    should use something like cvs2cl.pl ... -l "-r'last_tag' -r'this_tag'" but
#    I can't get cvs to ignore files which contain neither last_tag or this_tag
#    so ChangeLog contains lots of ancient stuff 

#    sets a cvs tag called gsdl-x_xx-distribution (unless -cvs_tag is set
#    in which case it uses that)

#    creates a copy of everything in cvs repository in $tmpdir

#    edits /tmp/gsdl/etc/VERSION, /tmp/gsdl/src/w32server/fnord.cpp
#    and /tmp/gsdl/cgi-bin/gsdlsite.cfg to use new version number
#    and default GSDLHOME

# temporary working directory
my $tmpdir = '/tmp';

# docs directory - up-to-date copy of everything to go in the docs directory 
# (including the README.txt) is expected to live here
my $docdir = '/home/nzdl/gsdl-docs';

# where the windows binaries live (including library.exe and server.exe)
# this currently relies on being a directory ending in "windows"
my $winbin = "$ENV{'GSDLHOME'}/bin/windows";

# ditto for linux binaries (don't forget getpw)
my $linuxbin = "$ENV{'GSDLHOME'}/bin/linux";

my $cvsanon = ':pserver:cvs_anon@cvs.scms.waikato.ac.nz:2402/usr/local/global-cvs/gsdl-src';


use parsargv;
use util;

use Cwd;


sub print_usage {
    print STDERR "\n";
    print STDERR "create_distributions.pl: Packages up Greenstone distributions.\n\n";
    print STDERR "  usage: $0 [options]\n\n";
    print STDERR "  options:\n";
    print STDERR "   -version_num           version number of distribution (x.xx)\n";
    print STDERR "   -cvs_tag               cvs tag from which to create distributions\n";
    print STDERR "                          - if not set latest versions will be used and\n";
    print STDERR "                          a tag will be set\n";
    print STDERR "   -no_cdrom              don't create cd-rom version\n";
    print STDERR "   -no_cols               don't attempt to create any collection distributions\n";
    print STDERR "   -only_cols             create collection distributions only\n";
    print STDERR "   -includecol            collection to include (by default all collections in\n";
    print STDERR "                          $ENV{'GSDLHOME'}/collect will be included\n";
    print STDERR "   -ignorecol             directory in $ENV{'GSDLHOME'}/collect to ignore (i.e.\n";
    print STDERR "                          don't include as collection in distribution)\n";
    print STDERR "   -output_dir            directory to output distributions to\n";
    print STDERR "   -NoChangeLog           don't create ChangeLog\n";
    print STDERR "   -UseExistingLog        use $ENV{'GSDLHOME'}/ChangeLog rather than creating one\n";
    print STDERR "   -ChangeLogDate         date from which to begin ChangeLog - note that ChangeLog\n";
    print STDERR "                          will always run from date to most recent commits, even if\n";
    print STDERR "                          cvs_tag is for a previous revision\n\n";
}

&main ();

sub main {
    if (!parsargv::parse(\@ARGV, 
			 'version_num/\d\.\d\d[a-z]?', \$version_num,
			 'cvs_tag/.*/', \$cvs_tag,
			 'no_cdrom', \$no_cdrom,
			 'no_cols', \$no_cols,
			 'only_cols', \$only_cols,
			 'includecol/.*', \@includecols,
			 'ignorecol/.*', \@ignorecols,
			 'NoChangeLog', \$nochangelog,
			 'UseExistingLog', \$useexistinglog,
			 'ChangeLogDate/.*/', \$changelogdate,
			 'output_dir/.*/', \$output_dir)) {
	&print_usage();
	die "\n";
    }

    $output_dir = "." unless $output_dir =~ /\w/;
    mkdir ($output_dir, 0777) unless -d $output_dir;

    my $have_tag = 0;
    if ($cvs_tag !~ /\w/) {
	$cvs_tag = $version_num;
	$cvs_tag =~ s/\./\_/g;
	$cvs_tag = "gsdl-" . $cvs_tag . "-distribution";
	$have_tag = 1;
    }

    &create_changelog() unless ($nochangelog || $useexistinglog);

    if (!$only_cols) {

	if ($have_tag) {
	    # Tag gsdl repository
	    chdir ($ENV{'GSDLHOME'});
	    print STDERR "\ntagging gsdl with $cvs_tag\n";
	    # `cvs tag -F $cvs_tag`;

	    # Tag gli repository
	    chdir (&util::filename_cat($ENV{'GSDLHOME'}, "gli"));
	    print STDERR "\ntagging gli with $cvs_tag\n";
	    # `cvs tag -F $cvs_tag`;
	}

	# Export gsdl to $tmpdir
	print STDERR "\nexporting gsdl ($cvs_tag) to $tmpdir\n\n";
	chdir($tmpdir);
	# `cvs -d $cvsanon export -r $cvs_tag gsdl`;
	`cvs -d $cvsanon export -D "1 second ago" gsdl`;

	# Export gli to $tmpdir/gli
	print STDERR "\nexporting gli ($cvs_tag) to " . &util::filename_cat($tmpdir, "gsdl") . "\n\n";
	chdir(&util::filename_cat($tmpdir, "gsdl"));
	# `cvs -d $cvsanon export -r $cvs_tag gli`;
	`cvs -d $cvsanon export -D "1 second ago" gli`;

	# Compile gli
	print STDERR "\ncompiling gli...\n";
	chdir(&util::filename_cat($tmpdir, "gsdl", "gli"));
	`makegli.sh`;

	# JAR up the gli, then clean up the class files
	print STDERR "jarring gli...\n";
	chdir(&util::filename_cat($tmpdir, "gsdl", "gli", "classes"));
	`jar cvfm ../GLI.jar META-INF/MANIFEST.MF *.properties images/ org/`;
	chdir(&util::filename_cat($tmpdir, "gsdl", "gli"));
	`clean.sh`;

	# Remove bits used by none of the distributions
	&util::rm(&util::filename_cat($tmpdir, "gsdl", "perllib", "Kea-1.1.4", "aliweb.df"));
	&util::rm(&util::filename_cat($tmpdir, "gsdl", "perllib", "Kea-1.1.4", "cstr.df"));

	# copy ChangeLog into $tmpdir/gsdl
	&util::cp(&util::filename_cat($ENV{'GSDLHOME'}, "ChangeLog"), 
		  &util::filename_cat($tmpdir, "gsdl")) unless $nochangelog;

	# edit the VERSION and fnord.cpp files
	&edit_files();

	&create_windows_distribution();
	&create_unix_distribution();
	&create_source_distribution();
	&create_cdrom_distribution() unless $no_cdrom;
    }

    &create_collection_distributions() unless $no_cols;
}


sub create_windows_distribution {
    print STDERR "Creating Windows distribution...\n";

    my $windows_dist_dir = &util::filename_cat($output_dir, "gsdl-" . $version_num . "-win32");
    mkdir ($windows_dist_dir, 0777);

    # empty "collect" directory (just because all the other distributions have one)
    mkdir (&util::filename_cat($windows_dist_dir, "collect"), 0777);

    # docs directory (with none of the manuals), README.TXT, COPYING and Support.htm
    &install_docs ($windows_dist_dir, 1);

    # gsdl directory
    &install_gsdl ($windows_dist_dir);

    # gli directory (in gsdl)
    &install_gli($windows_dist_dir, "windows");

    # src directory
    &install_src ($windows_dist_dir, "windows");

    # Windows directory
    &install_windows_specific ($windows_dist_dir, 0);

    # we want to include the unbuilt bits of the demo collection too
    my $demodir = &util::filename_cat($windows_dist_dir, "gsdl", "collect", "demo");
    my $demoetc = &util::filename_cat($demodir, "etc");
    my $tmpdemo = &util::filename_cat($tmpdir, "gsdl", "collect", "demo");
    die "oops, no demo dir\n" unless -d $demodir;
    &util::cp (&util::filename_cat ($tmpdemo, "demo.col"), $demodir);
    &util::cp (&util::filename_cat ($tmpdemo, "etc", "dls.AZList.txt"), $demoetc);
    &util::cp (&util::filename_cat ($tmpdemo, "etc", "dls.Keyword.txt"), $demoetc);
    &util::cp (&util::filename_cat ($tmpdemo, "etc", "dls.Organization.txt"), $demoetc);
    &util::cp (&util::filename_cat ($tmpdemo, "etc", "dls.Subject.txt"), $demoetc);
    &util::cp_r (&util::filename_cat ($tmpdemo, "import"), $demodir);
    &util::cp_r (&util::filename_cat ($tmpdemo, "metadata"), $demodir);
}


sub create_unix_distribution {
    print STDERR "Creating Unix distribution...\n";

    my $unix_dist_dir = &util::filename_cat($output_dir, "gsdl-" . $version_num . "-unix");
    mkdir ($unix_dist_dir, 0777);

    # empty "collect" directory
    mkdir (&util::filename_cat($unix_dist_dir, "collect"), 0777);

    # docs directory (with none of the manuals), README.TXT, COPYING and Support.htm
    &install_docs ($unix_dist_dir, 1);

    # Don't need Windows README file
    &util::rm(&util::filename_cat($unix_dist_dir, "READMEru.txt-cp1251"));

    # Rename Unix README file
    &util::cp(&util::filename_cat($unix_dist_dir, "READMEru.txt-koi8-r"),
	      &util::filename_cat($unix_dist_dir, "READMEru.txt"));
    &util::rm(&util::filename_cat($unix_dist_dir, "READMEru.txt-koi8-r"));

    # gsdl directory
    &install_gsdl ($unix_dist_dir);

    # gli directory (in gsdl)
    &install_gli($unix_dist_dir, "unix");

    # src directory
    &install_src ($unix_dist_dir, "unix");

    # Unix directory
    &install_unix_specific ($unix_dist_dir);

    # Make sure all configure scripts are executable
    `cd $unix_dist_dir; pwd; find -name "configure" -exec chmod a+x {} \\;`;

    # we want to include the unbuilt bits of the demo collection too
    my $demodir = &util::filename_cat($unix_dist_dir, "gsdl", "collect", "demo");
    my $demoetc = &util::filename_cat($demodir, "etc");
    my $tmpdemo = &util::filename_cat($tmpdir, "gsdl", "collect", "demo");
    die "oops, no demo dir\n" unless -d $demodir;
    &util::cp (&util::filename_cat ($tmpdemo, "demo.col"), $demodir);
    &util::cp (&util::filename_cat ($tmpdemo, "etc", "dls.AZList.txt"), $demoetc);
    &util::cp (&util::filename_cat ($tmpdemo, "etc", "dls.Keyword.txt"), $demoetc);
    &util::cp (&util::filename_cat ($tmpdemo, "etc", "dls.Organization.txt"), $demoetc);
    &util::cp (&util::filename_cat ($tmpdemo, "etc", "dls.Subject.txt"), $demoetc);
    &util::cp_r (&util::filename_cat ($tmpdemo, "import"), $demodir);
    &util::cp_r (&util::filename_cat ($tmpdemo, "metadata"), $demodir);
}


sub create_source_distribution {
    print STDERR "Creating Source distribution...\n";

    my $source_dist_dir = &util::filename_cat($output_dir, "gsdl-" . $version_num . "-src");
    mkdir($source_dist_dir, 0777);

    my $gsdldir = &util::filename_cat ($source_dist_dir, "gsdl");

    # Copy the entire contents of the exported GSDL directory
    my $tmpgsdldir = &util::filename_cat($tmpdir, "gsdl");
    `cp -r $tmpgsdldir $source_dist_dir`;

    # We want the COPYING file in the source distribution too
    &util::cp(&util::filename_cat($docdir, "COPYING"), $gsdldir);

    # Remove the copied "images" and "macros" folders and copy over just the core languages
    my $gsdlimagesdir = &util::filename_cat($source_dist_dir, "gsdl", "images");
    &util::rm_r($gsdlimagesdir);
    &install_only_core_language_images(&util::filename_cat($tmpdir, "gsdl", "images"), $gsdlimagesdir);
    my $gsdlmacrosdir = &util::filename_cat($source_dist_dir, "gsdl", "macros");
    &util::rm_r($gsdlmacrosdir);
    &install_only_core_language_macros(&util::filename_cat($tmpdir, "gsdl", "macros"), $gsdlmacrosdir);

    # We don't want the compiled GLI classes in the source distribution (or the GS3 script)
    &util::rm(&util::filename_cat($source_dist_dir, "gsdl", "gli", "GLI.jar"));
    &util::rm(&util::filename_cat($source_dist_dir, "gsdl", "gli", "gli4gs3.sh"));

    # Make sure there is a dictionary_en.properties to prevent GLI problems
    &util::cp(&util::filename_cat($source_dist_dir, "gsdl", "gli", "classes", "dictionary.properties"),
	      &util::filename_cat($source_dist_dir, "gsdl", "gli", "classes", "dictionary_en.properties"));

    # (We don't include the built demo collection in the source distribution)
}


sub create_cdrom_distribution {
    print STDERR "Creating CD-ROM distribution...\n";

    my $cdrom_dist_dir = &util::filename_cat ($output_dir, "gsdl-" . $version_num . "-cdrom");
    mkdir ($cdrom_dist_dir, 0777);

    # collect directory (empty for now; we'll add collections later)
    mkdir (&util::filename_cat ($cdrom_dist_dir, "collect"), 0777);

    # docs directory
    &install_docs ($cdrom_dist_dir, 0);

    # gsdl directory
    &install_gsdl ($cdrom_dist_dir);

    # gli directory (in gsdl)
    &install_gli($cdrom_dist_dir, "cdrom");

    # src directory
    &install_src ($cdrom_dist_dir, "cdrom");

    # Windows directory
    &install_windows_specific ($cdrom_dist_dir, 1);

    # Unix directory
    &install_unix_specific ($cdrom_dist_dir);

    # for the cd-rom we want to include the unbuilt bits of the demo collection too
    my $demodir = &util::filename_cat($cdrom_dist_dir, "gsdl", "collect", "demo");
    my $demoetc = &util::filename_cat($demodir, "etc");
    my $tmpdemo = &util::filename_cat($tmpdir, "gsdl", "collect", "demo");
    die "oops, no demo dir\n" unless -d $demodir;
    &util::cp (&util::filename_cat ($tmpdemo, "demo.col"), $demodir);
    &util::cp (&util::filename_cat ($tmpdemo, "etc", "dls.AZList.txt"), $demoetc);
    &util::cp (&util::filename_cat ($tmpdemo, "etc", "dls.Keyword.txt"), $demoetc);
    &util::cp (&util::filename_cat ($tmpdemo, "etc", "dls.Organization.txt"), $demoetc);
    &util::cp (&util::filename_cat ($tmpdemo, "etc", "dls.Subject.txt"), $demoetc);
    &util::cp_r (&util::filename_cat ($tmpdemo, "import"), $demodir);
    &util::cp_r (&util::filename_cat ($tmpdemo, "metadata"), $demodir);
}


# isweb is 1 if it's one of the web distributions (i.e. if we don't
# want to install the manuals) - this shouldn't be called at all for
# windows web installation as it doesn't use docs at all (not much 
# point for self-extracting exe).
sub install_docs {
    my ($install_dir, $isweb) = @_;

    # docs directory, README*.txt, COPYING and Support.htm
    &util::cp_r (&util::filename_cat($docdir, "docs"), $install_dir);
    &util::cp (&util::filename_cat($docdir, "READMEen.txt"), $install_dir);
    &util::cp (&util::filename_cat($docdir, "READMEes.txt"), $install_dir);
    &util::cp (&util::filename_cat($docdir, "READMEfr.txt"), $install_dir);
    &util::cp (&util::filename_cat($docdir, "READMEru.txt-cp1251"), $install_dir);
    &util::cp (&util::filename_cat($docdir, "READMEru.txt-koi8-r"), $install_dir);
    &util::cp (&util::filename_cat($docdir, "COPYING"), $install_dir);
    &util::cp (&util::filename_cat($docdir, "Support.htm"), $install_dir);

    # Don't want Kazakh manuals for either distribution
    # &util::rm(&util::filename_cat($install_dir, "docs", "Install-kz.pdf"));
    # &util::rm(&util::filename_cat($install_dir, "docs", "User-kz.pdf"));
    # &util::rm(&util::filename_cat($install_dir, "docs", "Paper-kz.pdf"));

    # don't want manuals for web distributions
    if ($isweb) {
	my @manuals =
	    ("Install-en.pdf", "User-en.pdf", "Develop-en.pdf", "Paper-en.pdf", "Organize-en.pdf",
	     "Install-fr.pdf", "User-fr.pdf", "Develop-fr.pdf", "Paper-fr.pdf", "Organize-fr.pdf",
	     "Install-es.pdf", "User-es.pdf", "Develop-es.pdf", "Paper-es.pdf", "Organize-es.pdf",
	     "Install-ru.pdf", "User-ru.pdf", "Develop-ru.pdf", "Paper-ru.pdf", "Organize-ru.pdf");

	foreach $manual (@manuals) {
	    my $manualfile = &util::filename_cat ($install_dir, "docs", $manual);
	    if (-e $manualfile) {
		&util::rm($manualfile);
	    }
	}
    }

    # Don't want doc versions of manuals
    $rm_docs = "rm -r " . &util::filename_cat ($install_dir, "docs", "*.doc");
    `$rm_docs`;

    # Don't want latex versions of manuals
    $rm_latex = "rm -r " . &util::filename_cat($install_dir, "docs", "latex");
    `$rm_latex`;
}


sub install_gsdl {
    my ($install_dir) = @_;

    my $gsdldir = &util::filename_cat ($install_dir, "gsdl");
    mkdir ($gsdldir, 0777);

    my $gsdlbindir = &util::filename_cat ($gsdldir, "bin");
    mkdir ($gsdlbindir, 0777);
    &util::cp_r (&util::filename_cat ($tmpdir, "gsdl", "bin", "script"), $gsdlbindir);
    &util::cp_r (&util::filename_cat ($tmpdir, "gsdl", "bin", "java"), $gsdlbindir);
    &util::cp_r (&util::filename_cat ($tmpdir, "gsdl", "cgi-bin"), $gsdldir);
    &util::cp_r (&util::filename_cat ($tmpdir, "gsdl", "collect"), $gsdldir);
    &util::cp_r (&util::filename_cat ($tmpdir, "gsdl", "etc"), $gsdldir);

    my $gsdlimagesdir = &util::filename_cat ($gsdldir, "images");
    &install_only_core_language_images(&util::filename_cat($tmpdir, "gsdl", "images"), $gsdlimagesdir);
    # ...and garish images
    &util::cp_r(&util::filename_cat($tmpdir, "gsdl", "images", "garish"), $gsdlimagesdir);
    # &util::cp_r (&util::filename_cat ($tmpdir, "gsdl", "images"), $gsdldir);

    my $gsdlmacrosdir = &util::filename_cat ($gsdldir, "macros");
    &install_only_core_language_macros(&util::filename_cat($tmpdir, "gsdl", "macros"), $gsdlmacrosdir);
    # &util::cp_r (&util::filename_cat ($tmpdir, "gsdl", "macros"), $gsdldir);

    &util::cp_r (&util::filename_cat ($tmpdir, "gsdl", "mappings"), $gsdldir);
    &util::cp_r (&util::filename_cat ($tmpdir, "gsdl", "perllib"), $gsdldir);

    # Rename perllib/strings.rb to perllib/strings_en.rb
    &util::cp (&util::filename_cat ($gsdldir, "perllib", "strings.rb"),
	       &util::filename_cat ($gsdldir, "perllib", "strings_en.rb"));
    &util::rm (&util::filename_cat ($gsdldir, "perllib", "strings.rb"));

    # untar Ping.tgz
    my $wd = cwd;
    chdir (&util::filename_cat($gsdldir, "perllib", "cpan"));
    `tar xvzf Ping.tgz`;
    unlink ("Ping.tgz");
    chdir ($wd);

    # make sure that modelcol collection contains all the right 
    # empty directories
    my $modelindex = &util::filename_cat ($tmpdir, "gsdl", "collect", "modelcol", "index");
    &util::mk_all_dir ($modelindex) unless -d $modelindex;
    my $modelbuilding = &util::filename_cat ($tmpdir, "gsdl", "collect", "modelcol", "building");
    &util::mk_all_dir ($modelbuilding) unless -d $modelbuilding;
    my $modelarchives = &util::filename_cat ($tmpdir, "gsdl", "collect", "modelcol", "archives");
    &util::mk_all_dir ($modelarchives) unless -d $modelarchives;
    my $modelimport = &util::filename_cat ($tmpdir, "gsdl", "collect", "modelcol", "import");
    &util::mk_all_dir ($modelimport) unless -d $modelimport;
    my $modelperllib = &util::filename_cat ($tmpdir, "gsdl", "collect", "modelcol", "perllib");
    &util::mk_all_dir ($modelperllib) unless -d $modelperllib;
    my $modelimages = &util::filename_cat ($tmpdir, "gsdl", "collect", "modelcol", "images");
    &util::mk_all_dir ($modelimages) unless -d $modelimages;

    # demo collection needs to be pre-built
    my $collectdir = &util::filename_cat ($gsdldir, "collect");
    &util::rm_r (&util::filename_cat($collectdir, "demo"));
    if (!&get_built_collection ("demo", $collectdir)) {
	die "Couldn't get built version of demo collection\n";
    }
}


sub install_only_core_language_images
{
    my ($source_dir, $target_dir) = @_;
    mkdir($target_dir, 0777);

    # Copy all the English images (in the "images" directory)
    opendir(IMAGES_DIR, $source_dir) || die "Error: Could not open directory $source_dir\n";
    foreach $file (readdir(IMAGES_DIR)) {
	my $source_file = &util::filename_cat($source_dir, $file);
	if (-f $source_file) {  # Plain files only (ignore directories)
	    &util::cp($source_file, $target_dir);
	}
    }
    closedir(IMAGES_DIR);

    # Copy the core language (French, Spanish, Russian) images
    &util::cp_r(&util::filename_cat($source_dir, "es"), $target_dir);
    &util::cp_r(&util::filename_cat($source_dir, "fr"), $target_dir);
    &util::cp_r(&util::filename_cat($source_dir, "ru"), $target_dir);
}


sub install_only_core_language_macros
{
    my ($source_dir, $target_dir) = @_;
    mkdir($target_dir, 0777);

    # Language independent (theoretically) macrofiles
    my @basicmacrofiles = ("about.dm", "authen.dm", "base.dm", "browse.dm", "bsummary.dm",
			   "collect.dm", "dateqry.dm", "docs.dm", "document.dm",
			   "exported_home.dm", "extlink.dm", "extra.dm",
			   "garish.dm", "gli.dm", "gsdl.dm", "help.dm", "home.dm", "html.dm",
			   "nzdlhome.dm", "pref.dm", "query.dm", "status.dm", "style.dm",
			   "tip.dm", "translang.dm", "users.dm", "yourhome.dm");

    # Core language (English, French, Spanish, Russian) macrofiles 
    my @corelanguagemacrofiles = ("english.dm", "english2.dm", "french.dm", "french2.dm",
				  "spanish.dm", "spanish2.dm", "russian.dm", "russian2.dm",
				  "yourhome-es.dm", "yourhome-fr.dm");

    # Copy the macrofiles
    foreach $file ((@basicmacrofiles, @corelanguagemacrofiles)) {
	&util::cp(&util::filename_cat($source_dir, $file), $target_dir);
    }
}


sub install_gli
{
    my ($install_dir, $type) = @_;

    # Copy the Greenstone Librarian Interface
    my $source_dir = &util::filename_cat($tmpdir, "gsdl", "gli");
    my $target_dir = &util::filename_cat($install_dir, "gsdl");
    &util::cp_r($source_dir, $target_dir);

    my $gli_dir = &util::filename_cat($target_dir, "gli");

    # Make Unix scripts executable
    my $clean_sh = &util::filename_cat($gli_dir, "clean.sh");
    `chmod a+x $clean_sh`;
    my $document_sh = &util::filename_cat($gli_dir, "document.sh");
    `chmod a+x $document_sh`;
    my $gli_sh = &util::filename_cat($gli_dir, "gli.sh");
    `chmod a+x $gli_sh`;
    my $makegli_sh = &util::filename_cat($gli_dir, "makegli.sh");
    `chmod a+x $makegli_sh`;

    # Make sure there is a dictionary_en.properties to prevent GLI problems
    &util::cp(&util::filename_cat($gli_dir, "classes", "dictionary.properties"),
	      &util::filename_cat($gli_dir, "classes", "dictionary_en.properties"));

    # Remove unwanted stuff - all distributions
    &util::rm_r(&util::filename_cat($gli_dir, "buglist"));
    &util::rm_r(&util::filename_cat($gli_dir, "prototype"));

    # Don't need Greenstone 3 script
    &util::rm(&util::filename_cat($gli_dir, "gli4gs3.sh"));

    # Remove unwanted stuff - Unix distributions
    if ($type eq "unix") {
	# Don't need Windows scripts
	&util::rm(&util::filename_cat($gli_dir, "clean.bat"));
	&util::rm(&util::filename_cat($gli_dir, "document.bat"));
	&util::rm(&util::filename_cat($gli_dir, "gli.bat"));
	&util::rm(&util::filename_cat($gli_dir, "makegli.bat"));

	# Don't need Windows utilities
	&util::rm_r(&util::filename_cat($gli_dir, "winutil"));

	# Don't need Windows README file
	&util::rm(&util::filename_cat($gli_dir, "READMEru.txt-cp1251"));

	# Rename Unix README file
	&util::cp(&util::filename_cat($gli_dir, "READMEru.txt-koi8-r"),
		  &util::filename_cat($gli_dir, "READMEru.txt"));
	&util::rm(&util::filename_cat($gli_dir, "READMEru.txt-koi8-r"));
    }

    # Remove unwanted stuff - Windows distributions
    if ($type eq "windows") {
	# Don't need Unix scripts
	&util::rm(&util::filename_cat($gli_dir, "clean.sh"));
	&util::rm(&util::filename_cat($gli_dir, "document.sh"));
	&util::rm(&util::filename_cat($gli_dir, "gli.sh"));
	&util::rm(&util::filename_cat($gli_dir, "makegli.sh"));
    }
}


sub install_src {
    my ($install_dir, $type) = @_;

    my $srcdir = &util::filename_cat ($install_dir, "src");
    my $srcwindir = &util::filename_cat ($srcdir, "Windows");
    my $srcunixdir = &util::filename_cat ($srcdir, "Unix");
    mkdir ($srcdir, 0777);
    &util::cp_r (&util::filename_cat ($tmpdir, "gsdl", "lib"), $srcdir);
    &util::cp_r (&util::filename_cat ($tmpdir, "gsdl", "packages"), $srcdir);
    &util::cp_r (&util::filename_cat ($tmpdir, "gsdl", "src"), $srcdir);
    &util::cp (&util::filename_cat ($tmpdir, "gsdl", "Install.txt"), $srcdir);

    if ($type ne "unix") {
	mkdir ($srcwindir, 0777);
	&util::cp (&util::filename_cat ($tmpdir, "gsdl", "setup.bat"), $srcwindir);
	&util::cp (&util::filename_cat ($tmpdir, "gsdl", "win32.mak"), $srcwindir);
	&util::cp (&util::filename_cat ($tmpdir, "gsdl", "WIN32cfg.h"), $srcwindir);
    }

    if ($type ne "windows") {
	mkdir ($srcunixdir, 0777);
	&util::cp (&util::filename_cat ($tmpdir, "gsdl", "Makefile.in"), $srcunixdir);
	&util::cp (&util::filename_cat ($tmpdir, "gsdl", "acconfig.h"), $srcunixdir);
	&util::cp (&util::filename_cat ($tmpdir, "gsdl", "aclocal.m4"), $srcunixdir);
	&util::cp (&util::filename_cat ($tmpdir, "gsdl", "config.h.in"), $srcunixdir);
	&util::cp (&util::filename_cat ($tmpdir, "gsdl", "configtest.pl"), $srcunixdir);
	&util::cp (&util::filename_cat ($tmpdir, "gsdl", "configure"), $srcunixdir);
	# make sure configure script is executable
	my $configure_script = &util::filename_cat ($srcunixdir , "configure");
	`chmod a+x $configure_script`;
	&util::cp (&util::filename_cat ($tmpdir, "gsdl", "configure.in"), $srcunixdir);
	&util::cp (&util::filename_cat ($tmpdir, "gsdl", "config.sub"), $srcunixdir);
	&util::cp (&util::filename_cat ($tmpdir, "gsdl", "config.guess"), $srcunixdir);
	&util::cp (&util::filename_cat ($tmpdir, "gsdl", "install-sh"), $srcunixdir);
	&util::cp (&util::filename_cat ($tmpdir, "gsdl", "setup.bash"), $srcunixdir);
	&util::cp (&util::filename_cat ($tmpdir, "gsdl", "setup.csh"), $srcunixdir);
    }
}

# if $cd_rom is not true then we don't want to include the net16, net32,
# Win32s or netscape directories in the bin/windows directory (note that
# this currently means exportcol.pl will fail for all but cd-rom installed
# distributions)
sub install_windows_specific {
    my ($install_dir, $cd_rom) = @_;

    my $windir = &util::filename_cat ($install_dir, "Windows");
    my $winbindir = &util::filename_cat ($windir, "bin");
    mkdir ($windir, 0777);
    mkdir ($winbindir, 0777);
    &util::cp_r ($winbin, $winbindir);

    if (!$cd_rom) {
	&util::rm_r (&util::filename_cat ($winbindir, "windows", "Win32s"));
	&util::rm_r (&util::filename_cat ($winbindir, "windows", "netscape"));
    }

    # make sure there aren't any CVS directories laying around
    &remove_cvs_dirs ($windir);
}

sub install_unix_specific {
    my ($install_dir) = @_;

    my $unixdir = &util::filename_cat ($install_dir, "Unix");
    my $unixbindir = &util::filename_cat ($unixdir, "bin");
    mkdir ($unixdir, 0777);
    mkdir ($unixbindir, 0777);
    &util::cp (&util::filename_cat($tmpdir, "gsdl", "Install.sh"), $unixdir);

    # make sure Install.sh is executable
    my $install_sh = &util::filename_cat($unixdir, "Install.sh");
    `chmod a+x $install_sh`;

    &util::cp_r ($linuxbin, $unixbindir);
    # make sure linux binaries are all executable
    my $linuxbindir = &util::filename_cat($unixbindir, 'linux');
    `chmod -R a+x $linuxbindir`;

    # make sure there aren't any CVS directories laying around
    &remove_cvs_dirs ($unixdir);
}

sub create_collection_distributions {
    
    # work out which collections we want
    my @cols = ();
    if (scalar @includecols) {
	@cols = @includecols;
    } else {
	my $collectdir = &util::filename_cat($ENV{'GSDLHOME'}, "collect");

	opendir (COLLECTDIR, $collectdir) || die;
	my @cdirs = readdir COLLECTDIR;
	closedir COLLECTDIR;
	my %ignore = ();
	map { $ignore{$_} = ""; } @ignorecols;
	foreach $d (@cdirs) {
	    if ((-d &util::filename_cat($collectdir, $d)) && ($d ne ".") && ($d ne "..") && 
		($d ne "modelcol") && ($d ne "CVS") && (!defined $ignore{$d})) {
		push (@cols, $d);
	    }
	}
    }
    
    return unless scalar @cols;

    # create distributions
    foreach $collection (@cols) {
	if (&get_built_collection ($collection, $tmpdir)) {
	    &zip ("$collection-prebuilt", $collection, $tmpdir, 0);
	    &util::cp (&util::filename_cat($tmpdir, "$collection-prebuilt.tgz"), $output_dir);
	    &util::cp (&util::filename_cat($tmpdir, "$collection-prebuilt.zip"), $output_dir);
	} else {
	    print STDERR "ERROR: Couldn't create pre-built $collection collection\n";
	}
	&util::rm_r (&util::filename_cat ($tmpdir, $collection)) 
	    if -d &util::filename_cat ($tmpdir, $collection);

	if (&get_unbuilt_collection ($collection, $tmpdir)) {
	    &zip ($collection, $collection, $tmpdir, 0);
	    &util::cp (&util::filename_cat($tmpdir, "$collection.tgz"), $output_dir);
	    &util::cp (&util::filename_cat($tmpdir, "$collection.zip"), $output_dir);
	} else {
	    print STDERR "ERROR: Couldn't create unbuilt $collection collection\n";
	}
	&util::rm_r (&util::filename_cat ($tmpdir, $collection)) 
	    if -d &util::filename_cat ($tmpdir, $collection);
    }
}

# gets all the right bits of a built collection from 
# $GSDLHOME/collect and copies them to $collect_dir
# returns 1 if successful, 0 if not
sub get_built_collection {
    my ($colname, $collect_dir) = @_;

    my $from_dir = &util::filename_cat ($ENV{'GSDLHOME'}, "collect", $colname);
    if (!-d $from_dir) {
	print STDERR "\nERROR: No collection at $from_dir\n";
	return 0;
    }
    
    my $to_dir = &util::filename_cat ($collect_dir, $colname);
    mkdir ($to_dir, 0777) unless -d $to_dir;
    
    # get the built indexes
    my $index_dir = &util::filename_cat ($from_dir, "index");
    if (-d $index_dir) {
	# if build.cfg exists we'll assume collection is built ok
	if (-e &util::filename_cat ($index_dir, "build.cfg")) {
	    &util::cp_r ($index_dir, $to_dir);
	} else {
	    print STDERR "\nERROR: no build.cfg at $index_dir (collection not built?)\n";
	    rmdir ($to_dir);
	    return 0;
	}
    } else {
	print STDERR "\nERROR: collection at $from_dir appears unbuilt (no index directory)\n";
	return 0;
    }
    &util::cp_r ($index_dir, $to_dir);
    
    # get the collect.cfg file
    mkdir (&util::filename_cat($to_dir, "etc"), 0777);
    &util::cp (&util::filename_cat($from_dir, "etc", "collect.cfg"),
	       &util::filename_cat($to_dir, "etc"));

    # get the images directory
    my $from_images = &util::filename_cat ($from_dir, "images");
    &util::cp_r ($from_images, $to_dir) if -d $from_images;
    
    # make sure there aren't any CVS directories laying around
    &remove_cvs_dirs ($to_dir);

    &edit_collect_cfg (&util::filename_cat($to_dir, "etc", "collect.cfg"), $colname);
    &create_version_file (&util::filename_cat($to_dir, "etc", "VERSION"), 0);

    return 1;
}

# gets all the right bits of an unbuilt collection from 
# $GSDLHOME/collect and copies them to $collect_dir
# returns 1 if successful, 0 if not
sub get_unbuilt_collection {
    my ($colname, $collect_dir) = @_;

    my $from_dir = &util::filename_cat ($ENV{'GSDLHOME'}, "collect", $colname);
    if (!-d $from_dir) {
	print STDERR "\nERROR: No collection at $from_dir\n";
	return 0;
    }
    
    my $to_dir = &util::filename_cat ($collect_dir, $colname);
    mkdir ($to_dir, 0777) unless -d $to_dir;

    # get the unbuilt data (either import or archives)
    my $have_import = 0;
    my $import_dir = &util::filename_cat ($from_dir, "import");
    if (-d $import_dir && opendir (IMPORTDIR, $import_dir)) {
	my @importfiles = readdir IMPORTDIR;
	closedir IMPORTDIR;
	# if the import directory isn't empty we'll assume everything's ok
	if (scalar @importfiles) {
	    $have_import = 1;
	    &util::cp_r ($import_dir, $to_dir);
	    mkdir (&util::filename_cat ($to_dir, "archives"), 0777);
	}
    }
    if (!$have_import) {
	# see if we've got archives then (check for archives.inf)
	if (-e &util::filename_cat ($from_dir, "archives", "archives.inf")) {
	    &util::cp_r (&util::filename_cat($from_dir, "archives"), $to_dir);
	} else {

	    print STDERR "$collection collection appears to have no valid\n";
	    print STDERR "import or archives data\n";
	    &util::rm_r ($to_dir);
	    return 0;
	}
    }
    
    # get the etc directory
    &util::cp_r (&util::filename_cat ($from_dir, "etc"), $to_dir);

    # get the perllib directory
    &util::cp_r (&util::filename_cat ($from_dir, "perllib"), $to_dir);

    # get the images
    &util::cp_r (&util::filename_cat ($from_dir, "images"), $to_dir);
    
    mkdir (&util::filename_cat ($to_dir, "building"), 0777);
    mkdir (&util::filename_cat ($to_dir, "index"), 0777);

    # make sure there aren't any CVS directories laying around
    &remove_cvs_dirs ($to_dir);

    &edit_collect_cfg (&util::filename_cat($to_dir, "etc", "collect.cfg"), $colname);
    my $preimported = 0;
    $preimported = 1 unless $have_import;
    &create_version_file (&util::filename_cat($to_dir, "etc", "VERSION"), $preimported);

    return 1;
}

sub create_changelog {

    my ($tag, $date, $file);

    my $datefile = &util::filename_cat ($ENV{'GSDLHOME'}, "DistDates");
    if ($changelogdate !~ /\w/) {
	# get date from $GSDLHOME/DistDates (and update DistDates)
	open (DATES, $datefile) || die "can't open $datefile\n";
	my $line = "";
	while (defined ($line = <DATES>)) {
	    if ($line =~ /\w/) {
		($tag, $date) = $line =~ /^(\S+)\t(.*)$/;
		$changelogdate = $date unless ($tag eq $cvs_tag);
	    }
	    $file .= $line;
	}
	close DATES;
    }

    if ((!defined $tag) || ($tag ne $cvs_tag)) {
	open (DATES, ">$datefile") || die;
	print DATES $file if defined $file;
	print DATES "$cvs_tag\t" . `date`;
	close DATES;
    }

    print STDERR "Creating ChangeLog from $changelogdate to most recent\n";

    chdir($ENV{'GSDLHOME'});
    my $cmd = "cvs2cl.pl -P -F trunk -r -S -l \"-d'$changelogdate<tomorrow'\"";
    system ($cmd);
}

# edits the gsdlsite.cfg file to set GSDLHOME
# makes a copy of the initial version of gsdlsite.cfg in
# /tmp (if it doesn't exist already).
sub edit_gsdlsite {
    my ($gsdlhome) = @_;

    my $gsdlsite_file = &util::filename_cat ($tmpdir, "gsdl", "cgi-bin", "gsdlsite.cfg");
    my $tmp_gsdlsite_file = &util::filename_cat ($tmpdir, "gsdlsite.cfg");

    if (-e $tmp_gsdlsite_file) {
	&util::cp ($tmp_gsdlsite_file, $gsdlsite_file);
    } else {
	&util::cp ($gsdlsite_file, $tmp_gsdlsite_file);
    }

    open (GSDLSITE, $gsdlsite_file) || die;
    my $line = ""; my $file = ""; my $found = 0;
    while (defined ($line = <GSDLSITE>)) {
	if ($line =~ s/\*\*GSDLHOME\*\*/$gsdlhome/g) {
	    $found = 1;
	}
	$file .= $line;
    }
    close GSDLSITE;

    if (!$found) {
	die "ERROR: $gsdlsite_file contains no **GSDLHOME** string\n";
    }

    open (GSDLSITE, ">$gsdlsite_file") || die;
    print GSDLSITE $file;
    close GSDLSITE;
}

# currently just checks that iconcollection fields are correct and that
# creator and maintainer fields are set to greenstone@cs.waikato.ac.nz
sub edit_collect_cfg {
    my ($collect_cfg_file, $collname) = @_;

    open (FILE, $collect_cfg_file) || die "couldn't open $collect_cfg_file\n";
    my $line = ""; my $file = "";
    while (defined ($line = <FILE>)) {
	$line =~ s/^((?:creator|maintainer)\s+\"?)\w+@\w+(\"?)/$1greenstone\@cs.waikato.ac.nz$2/ix;
	# !! This will stuff up if there are handle language qualifiers eg. [l=en] !!
	# $line =~ s/^(collectionmeta\s+\"?iconcollection(?:small)?\"?\s+\"?).*?($collname\/images\/)/$1_httpprefix_\/collect\/$2/ix;
	$file .= $line;
    }
    close FILE;

    open (FILE, ">$collect_cfg_file") || die;
    print FILE $file;
    close FILE;
}

# the "collection release" is the version of the content - it should only change if the 
# collections content is changed in some way
# the "build version" is the build version of Greenstone when the collection distribution
# was created

# recent build version changes were:
# 2.0 - 2.1: plugins were altered to take input_encoding (and other) options. GB plugins
#            were removed. numwords and numsections statistics were added.
#            All build version 2.0 collections other than those that suddenly required
#            the input_encoding option (i.e. Arabic and Chinese) may still be built and
#            viewed using build verion 2.1 software (numwords and numsections won't be
#            available though).

sub create_version_file {
    my ($version_file, $preimported) = @_;
    
    open (FILE, ">$version_file") || die;
    
    print FILE "collection release: 1.1\n";
    print FILE "build version: 2.1\n";
    print FILE "pre-imported\n" if $preimported;

    close FILE;
}

# simply recurses directory structure beginning at $dir
# and deletes any CVS administrative directories it comes 
# across
sub remove_cvs_dirs {
    my ($dir) = @_;

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

    opendir (DIR, $dir) || die;
    my @files = readdir DIR;
    closedir DIR;

    foreach $file (@files) {
	next if $file =~ /^\.\.?$/;
	my $fullpath = &util::filename_cat ($dir, $file);
	if (-d $fullpath) {
	    if ($file eq "CVS") {
		&util::rm_r ($fullpath);
	    } else {
		&remove_cvs_dirs ($fullpath);
	    }
	}
    }
}

# mode is 0 to create .zip and .tgz, 1 to create .zip only, and 2 to create
# .tgz only
sub zip {
    my ($zip_to, $zip_from, $dir, $mode) = @_; 

    chdir ($dir);

    if ($mode != 2) {
	my $to = $zip_to . ".zip";
	unlink ($to) if -e $to;
	print STDERR "zipping up $to\n";
	`zip -r $to $zip_from`;
    }
    if ($mode != 1) {
	my $to = $zip_to . ".tgz";
	unlink ($to) if -e $to;
	print STDERR "tarring and gzipping $to\n";
	print STDERR "tar cvzf $to $zip_from\n";
	system ("tar cvzf $to $zip_from");
    }
}

sub edit_files {
    # edit VERSION file
    my $version_file = &util::filename_cat ($tmpdir, "gsdl", "etc" , "VERSION");
    open (VERSION, $version_file) || die "failed to open $version_file\n";
    my $found = 0; my $line = ""; my $file = "";
    while (defined ($line = <VERSION>)) {
	if ($line =~ s/(gsdl version: )x\.xx/$1$version_num/) {
	    $found ++;
	} elsif ($line =~ s/(cvs tag: )gsdl-x_xx-distribution/$1$cvs_tag/) {
	    $found ++;
	}
	$file .= $line;
    }
    close VERSION;
    if ($found != 2) {
	die "error while editing $version_file\n";
    } 
    
    open (VERSION, ">$version_file") || die;
    print VERSION $file;
    close VERSION;
    
    # edit gsdlconf.h
    my $gsdlconf_file = &util::filename_cat ($tmpdir, "gsdl", "lib", "gsdlconf.h");
    open (GSDLCONF, $gsdlconf_file) || die;
    $found = 0; $line = ""; $file = "";
    while (defined ($line = <GSDLCONF>)) {
	if ($line =~ s/(\#define GSDL_VERSION \")x\.xx(\")/$1$version_num$2/) {
	    $found ++;
	}
	$file .= $line;
    }
    close GSDLCONF;
    if (!$found) {
	die "error while editing $gsdlconf_file\n";
    } 
    
    open (GSDLCONF, ">$gsdlconf_file") || die;
    print GSDLCONF $file;
    close GSDLCONF;
}

END {
    # remove any temporary files we created
    print STDERR "\ndeleting temporary files\n";
    my $tmp_gsdlsite_file = &util::filename_cat ($tmpdir, "gsdlsite.cfg");
    if (-e $tmp_gsdlsite_file) {
	print STDERR "$tmp_gsdlsite_file\n";
	unlink($tmp_gsdlsite_file);
    }
    my $tmp_gsdlhome = &util::filename_cat ($tmpdir, "gsdl");
    if (-d $tmp_gsdlhome) {
	print STDERR "$tmp_gsdlhome\n";
	&util::rm_r ($tmp_gsdlhome);
    }
}
