#!/usr/bin/perl

#------------------------------------------------------------------------
# Author: C. Edward Chow
# Date:   22 December 1995
# Draft:  1.0
# Simple Perl script to answer grade query
#------------------------------------------------------------------------

# Make sure use GET instead Get or get on the following matching string

if ($ENV{'REQUEST_METHOD'} eq "GET") { $buffer = $ENV{'QUERY_STRING'}; }
else { read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'}); }

print "Content-type: text/html\n\n";
print "<HTML><HEAD>\n";
print "</HEAD><BODY BGColor=\"#ffd39b\" TEXT=\"#2222222\">\n";
print "<H1>Buffer=$buffer</H1>\n";
print "</BODY></HTML>"; 

@nvpairs = split(/&/, $buffer);
foreach $pair (@nvpairs)
{
    ($name, $value) = split(/=/, $pair);

    $value =~ tr/+/ /;
    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
    print "name=$name, value=$value<br>";
    $answers{$name} = $value;
}

$login = $answers{'login'};
$passwd = $answers{'passwd'};
open(IN, "list.txt");
$found = 0;
while (<IN>) {
    if (/$login/) {
        @fields = split(/:/);
        $encryptedPasswd = $fields[1];
        $fullname = $fields[5];
	$found = 1;
        last;
    }
}
if ($found == 0) {
    print "login not correct!";
    die;
}
$try = 1;
while ($try) {
   if (crypt($passwd, $encryptedPasswd) eq $encryptedPasswd) {
      print "login correct!\n"; 
      last;
   } else {
      print "password not correct!";
      die;
   }
}
close(IN);
#create unique file name
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
$mon++;  # month is 0 indexed
$filename = "$login\_$year\_$mon\_$mday:$hour:$min:$sec";
open(OUT, ">cs301midterm/$filename");
print OUT $buffer;
close(OUT);
$command="mail -s 'cs301 midterm from". $login . "' chow < $class\/$examine\/$filename";
system("$command");
