#!/usr/local/bin/perl 

require "cgi-lib.pl";
## require "cgi-utils.pl";
binmode STDIN;
&ReadParse(*input);

$remote_host=$ENV{'REMOTE_HOST'};
if ($remote_host =~/sdsc\.edu/) {
   print "Content-type: text/html\n\n";
   print "<B>Status: 200 OK, You are from SDSC's domain.</B><BR><P>\n";
}
else {
   print "Content-type: text/html\n\n";
   print "<B>Status 400 Bad Request, You must be part of SDSC's domain.</B>\n";
   print "remote_host is $remote_host\n";
   exit(0);
}


## read(STDIN, $input, $ENV{'CONTENT_LENGTH'});
@stuff= split(/&/,$input);
@input1 = split(/=/, $stuff[0]);

# convert hex characters passed in directory value
 for $i (0..$#input1)
 { 
        # convert hex versions of :,/,\ to ascii
        $input1[$i] =~s/%(..)/pack("c",hex($1))/ge;
   }

$direct = $input1[1];
if ($direct=~/\.\./) {
##   print "Content-type: text/html\n\n";
   print "<B>Sorry, You have entered invalid characters into the path.</B><BR><P>\n";
   print "Please check your specification and try again.\n";
   exit(0);
}

@input2 = split(/=/, $stuff[1]);
$filena = $input2[1];
## $topdir = "/misc/www/users/damartin/PWT";
$topdir = "/projects/us/bio2/PWT/demo/qry";
$direct = $topdir.$direct;

 chdir("$direct");
 opendir(ROOT, "$direct");
 @files = readdir(ROOT);

if ("$filena")
{
     # check to see if file is in the directory
     for $i (0..$#files){
	$temp = $files[$i];
	if ($filena eq $temp) {
     	    # print contents of the file
	    open(FILE,$filena);
##	    print "Content-type: text/plain\n\n";
     	    while($input=<FILE>)
	     {
	   	print "$input";
	     }
	$isafile = 1;
	} # end if
     }  # end for 
if (!$isafile) { 
##	print "Content-type: text/html\n\n";
	print "<HEAD><TITLE>Query Results</TITLE></HEAD>\n";
	print "<BODY><H1><STRONG> Could not find file: </STRONG>", $filena, "</H1><P>\n";
	print "</BODY>\n";
	} # end if

} # end if

else
{
## print "Content-type: text/html\n\n";

print "<HEAD><TITLE>Query Results</TITLE></HEAD>\n";

print "<BODY><H2><STRONG>Directory: </STRONG>", $direct, "</H2><P><PRE>\n";
     for $i (0..$#files)
     {
           if (-d $files[$i]) { print "<STRONG>", $files[$i], "</STRONG><EM> (directory)</EM>\n"; }

	else { print "<TT>", $files[$i], "</TT>\n"; }
     }
    print "</PRE></BODY>\n";
}


