#!/usr/bin/perl -w

use CGI;
use usabcgi;

sub init_cgi
{
    my $line = <STDIN>;
    my $cgi;

    if ((defined $line) && ($line ne "")) {
	$cgi = new CGI($line);
    }
    else {
	$cgi = new CGI();
    }

    return $cgi;
}

sub clean_param
{
    my ($cgi,$param) = @_;

    my $val = $cgi->param($param);
    $val =~ s/[\r\n]+$// if (defined $val);

    return $val;
}

sub safe_val
{
    my ($val) = @_;

    # ensure only alpha-numeric plus a few other special chars

    $val =~ s/[^[:alnum:]@\.\/\-]//g if (defined $val); 

    return $val;
}

sub run_gencmd
{
    my ($prog,$col,$cgi) = @_;

    my @arg_keys = $cgi->param;

    my $cmd = "source setup.bash > /dev/null ; $prog.pl ";

    foreach my $k ( @arg_keys ) {
	my $arg_val = clean_param($cgi,$k);
	# ensure only alphanumeric, plus a few special chars
	$arg_val = safe_val($arg_val);
	$cmd .= " -$k $arg_val"
    }

    $cmd .= " $col" if (defined $col);

    my $status;

    if (open(PIN,"$cmd 2>&1 |")) {
	while (defined (my $line=<PIN>)) {
	    print STDOUT $line;
	}
	close(PIN);

	$status = $?;

	# print STDOUT "Exit status: $status\n";
    }
    else {
	print STDOUT "Error: unable to execute cmd: $cmd\n";
	$status = -1;
    }

    return $status;
}


sub run_buildcol
{
    my ($col,$cgi) = @_;
    
    if (defined $col) {
	chdir("collect/$col");
	`rm -rf building/*; `;
	chdir("../..");
    }

    my $status = run_gencmd("buildcol",$col,$cgi);

    if ($status == 0) {
	if (defined $col) {
	    chdir("collect/$col");
	    `rm -rf index/*; cp -r building/. index/.`;
	    chdir("../..");
	}
    }
    else {

	# An error has occured
    }
}


sub run_deldir
{
    my ($col,$cgi) = @_;

    chdir("collect");

    my $dir = clean_param($cgi,"dir");
    $dir = "" if ($dir eq ".");

    my $cmd = "/bin/rm -rf $col/$dir";

    my $output = `$cmd`;

    chdir("..");
}

sub main
{
    print "Content-type:text/plain\n\n";

    my $cgi = init_cgi();

    my ($gsdlhome) = usabcgi::get_config_info("gsdlhome");
    chdir($gsdlhome);

    my $cmd = clean_param($cgi,"cmd");
    $cgi->delete("cmd");
    $cmd =~ s/\..*$//;
    $cmd = safe_val($cmd);

    my $col = clean_param($cgi,"c");
    if ((!defined $col) || ($col =~ m/^\s*$/)) {
	print "Content-type:text/plain\n\n";
	print "Error: No collection name specified\n";
	exit;
    }

    $cgi->delete("c");
    $col = safe_val($col);

    if ($cmd eq "mkcol") {
	run_gencmd($cmd,$col,$cgi);
    }
    elsif ($cmd eq "import") {
	run_gencmd($cmd,$col,$cgi);
    }
    elsif ($cmd eq "buildcol") {
	run_buildcol($col,$cgi);
    }
    elsif ($cmd eq "deldir") {
	run_deldir($col,$cgi);
    }
    else {
	print "Error: unrecognised command: '$cmd'\n";
	exit 1;
    }
    
}

&main();

