#!/usr/bin/perl -w

use gsdlCGI;

sub load_gsdl_utils
{
    my ($gsdlhome) = @_;

    require "$gsdlhome/perllib/util.pm";
}

sub main
{
    my $gsdl_cgi = new gsdlCGI("+cmdline");

    $gsdl_cgi->setup_gsdl();
    my $gsdlhome = $ENV{'GSDLHOME'};

    load_gsdl_utils($gsdlhome);

    my $col = $gsdl_cgi->clean_param("c");
    if (!defined $col) {
      $gsdl_cgi->generate_error("No collection specified.");
    }

    my $dir = $gsdl_cgi->clean_param("dir");
    $dir = "\"\"" if ((!defined $dir) || ($dir eq "."));

    my $accept_expr = $gsdl_cgi->clean_param("a");
    if(($accept_expr eq "") || (!defined $accept_expr)) {
	$accept_expr = "";
    }
    else {
	$accept_expr = "-accept " . $accept_expr;
    }

    my $reject_expr = $gsdl_cgi->clean_param("r");
    if(($reject_expr eq "") || (!defined $reject_expr)) {
	$reject_expr = "";
    }
    else {
	$reject_expr = "-reject " . $reject_expr;
    }

    my $zip_dirname = "";

    if ($col =~ m/^\//) { 
	# leading / at start denotes special "cols" such as "/tmp"

	$zip_dirname = $gsdlhome;
	$col =~ s/^\///;
    }
    else {
	$zip_dirname = &util::filename_cat($gsdlhome,"collect");
    }
    
    my $java = $gsdl_cgi->check_for_java();

    my $classpath 
	= &util::filename_cat($gsdlhome,"bin","java","SignedGatherer.jar");
    my $java_prog = "org.greenstone.gatherer.util.Zipup";
    my $java_args = "$zip_dirname $col $dir $accept_expr $reject_expr";
    my $java_cmd = "$java -classpath $classpath $java_prog $java_args";

    my $java_output = `$java_cmd`;

    my $status = $?;

    if ($status>0) {
	$status = $status/256;
	my $exit_status = "Exit status: $status\n";
	my $mess = "Java failed: $java_cmd\n--\n$java_output\n$exit_status";
	$gsdl_cgi->generate_error($mess);
    }
	
    my $zip_filename = &util::filename_cat($zip_dirname,"$col.zip");

    if (open(PIN,"<$zip_filename")) {
 	binmode(PIN);

 	my $buf;
 	my $num_bytes = 0;

	print STDOUT "Content-type:application/zip\n\n";

 	while (read(PIN,$buf,1024)>0) {
 	    print STDOUT $buf;
 	    $num_bytes += length($buf);
 	}

 	close(PIN);
    }
    else {
        my $mess = "Unable to read in $zip_filename\n  $!";
	$gsdl_cgi->generate_error($mess);
    }
    
    unlink "$zip_filename";
}

&main();

