#!/usr/bin/perl -w

use gsdlCGI;

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

    my $gsdlhome = $gsdl_cgi->get_config_info("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 = "";
	print "not using accept";
    }
    else {
	$accept_expr = "-accept " . $accept_expr;
    }

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

    if ($col =~ m/^\//) { 
	# leading / at start denotes special "cols" such as "/tmp"
	$gsdl_cgi->checked_chdir("$gsdlhome");
	$col =~ s/^\///;
    }
    else {
	$gsdl_cgi->checked_chdir("$gsdlhome/collect");
    }
    
    `java -classpath $gsdlhome/bin/java/SignedGatherer.jar org.greenstone.gatherer.util.Zipup $gsdlhome/ $col $dir $accept_expr $reject_expr`;
    
    my $pipe_cmd = "cat $col.zip"; # Unix specific
    
    if (open(PIN,"$pipe_cmd |")) {
 	binmode(PIN);

 	my $buf;
 	my $num_bytes = 0;

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

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

 	close(PIN);

 	my $status = $?;
    }
    else {
        $gsdl_cgi->generate_error("Unable to pipe input from: $pipe_cmd");
    }
    
    unlink "$col.zip";
}

&main();

