#!/usr/local/bin/perl
# -----------------------------------------------------------------
# bdtool.pl
# 
# Author: Mic Bowman and Satya Venneti
#
# Create the initial page for the validation database maintenance
# scripts.
# -----------------------------------------------------------------
$ENV{"HARVEST_HOME"} = "/usr/local/harvest" 
	if (!defined($ENV{"HARVEST_HOME"}));
$ENV{"HSR_HOME"} = "$ENV{'HARVEST_HOME'}/gatherers/HSR";
push(@INC,$ENV{"HSR_HOME"} . "/lib");
require 'cgi.pl';
require 'hsrlibrary.pl';
require 'bdlibrary.pl';

# -----------------------------------------------------------------
# BD_Apply
# -----------------------------------------------------------------
sub BD_Apply {
    local($stype,$shome,$sfile,$sop) = @_;
    local($type,$desc);
    local($thome,%tlist,$tname);

    $thome = $Config{"Tools.Home"};
    %tlist = &BD_ReadTools;
    $tname = join('&',$sop,$stype);

    &CGIError("This tool is not defined: $sop")
	if ((! defined $tlist{$tname}) || ($tlist{$tname} !~ /\S/));
    &CGIError("Unable to locate tool: $sop")
	if (! -r "$thome/$sop");

    # Be very careful about what we pass as parameters to the system call
    $desc = $tlist{$tname};
    &CGIError("Invalid server path: $shome")
	if ($shome !~ m@^[-a-zA-Z/.]+$@); # No special characters
    &CGIError("Invalid description file: $sfile")
	if ($sfile !~ m@^[-a-zA-Z/.]+$@); # No special characters
    
    # Make sure the file is in the descriptions home directory
    &CGIError("Invalid description file: $sfile")
	if (index($sfile,$Config{"Descriptions.Home"}) != 0);

    # Create the pipe and read the output
    open(SPIPE,"$thome/$sop $stype $sfile $shome|") ||
	&CGIError("Unable to apply tool $sop");

    while (<SPIPE>) {
	print $_;
    }

    close(SPIPE);
}

# -----------------------------------------------------------------
# Main
# -----------------------------------------------------------------
sub Main
{
    local($stype,$shome,$sfile,$sop);

    &HSR_Initialize;

    &CGIHeader;
    &CGIParse;
    &CGIError("Server type unspecified") 
	if ((! defined $in{"TYPE"}) || ($in{"TYPE"} !~ /\S/));
    &CGIError("Server home unspecified") 
	if ((! defined $in{"HOME"}) || ($in{"HOME"} !~ /\S/));
    &CGIError("Server description unspecified") 
	if ((! defined $in{"FILE"}) || ($in{"FILE"} !~ /\S/));
    &CGIError("No operation specified")
	if ((! defined $in{"OP"}) || ($in{"OP"} !~ /\S/));

    $stype = $in{"TYPE"};
    $shome = $in{"HOME"};
    $sfile = $in{"FILE"};
    $sop = $in{"OP"};

    &BD_Apply($stype,$shome,$sfile,$sop);
}

# -----------------------------------------------------------------
&Main;
exit(0);
