#!/usr/bin/perl -w


use gsdlCGI;


sub main
{
    my $gsdl_cgi = new gsdlCGI();
    my $gsdlhome = $gsdl_cgi->get_config_info("gsdlhome");

    my $col = $gsdl_cgi->clean_param("c");
    if ((!defined $col) || ($col =~ m/^\s*$/)) {
	$gsdl_cgi->generate_error("No collection name specified");
    }

    my $dir = $gsdl_cgi->clean_param("dir");
    if ((!defined $dir) || ($dir =~ m/^\s*$/)) {
	$gsdl_cgi->generate_error("No directory name specified");
    }

    $dir = "" if (($dir eq ".") || ($dir =~ m/^\.\./));

    my $zip_content = $gsdl_cgi->clean_param("zip");
    my $zip_fname = "$col.zip";

    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");
    }

    my $col_dir = "$col/$dir"; # Unix specific
    $gsdl_cgi->rm_rf($col_dir);
    if (!-e $col_dir) {
	my $mkdir_cmd = "mkdir $col_dir";
	$gsdl_cgi->unix_cmd($mkdir_cmd);
    }

    if (open(ZOUT,"> $zip_fname")) {
	
	my $ZIN = $gsdl_cgi->upload('zip');
	binmode($ZIN);

	my $buf;
	my $num_bytes = 0;

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

	close($ZIN);
	close(ZOUT);


##	print STDERR "**** Debug as /tmp/XXX.zip\n";
##	`cp $zip_fname /tmp/XXX.zip`;

	`java -classpath $gsdlhome/bin/java/SignedGatherer.jar org.greenstone.gatherer.util.Unzip $gsdlhome/ $zip_fname`;

	unlink "$zip_fname";

	$gsdl_cgi->generate_ok_message("$dir or $col uploaded successfully.");
    }
    else {
	$gsdl_cgi->generate_error("unable to open $zip_fname");
    }
}

&main();

