#!/usr/bin/perl -w

# CGI-script prints a list of students in a group, specified by the
# 'group' query parameter. Group list is read from
# '/home/02/akolosov/st/<group>.txt' file

# Parse query string.
if (length ($ENV{'QUERY_STRING'}) > 0) {
    $buffer = $ENV{'QUERY_STRING'};
    @pairs = split(/&/, $buffer);
    foreach $pair (@pairs){
        ($name, $value) = split(/=/, $pair);
        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
        $query{$name} = $value; 
    }
}

print "Content-Type: text/html;charset=UTF-8\r\n\r\n";

print "<!doctype html>\n";
print "<html>\n";
print "<head></head>\n";
print "<body>\n";

print "<h1>Здравствуйте</h1>\n";

# Get remote address from CGI environment
printf("<p>Ваш IP-адрес %s</p>", $ENV{"REMOTE_ADDR"});

# Check if 'group' parameter doesn't contain any other symbols than
# digits
if ($query{'group'} =~ /\d+/) {
    print "<h2>Группа $query{'group'}</h2>";
    print "<ol>\n";

    # Open the group list file
    open STUDS, "/home/02/akolosov/st/$query{'group'}.txt" or die $!;
    
    # for each line in file print HTML list item with student name and
    # email
    while (<STUDS>) { 
        chomp;
        
        # Parse student info
        ($n, $name, $email) = split(',', $_);
        
        # Print a student
        print "<li>\n";
        print "\t<a href='mailto:$email'>$name</a>\n"; 
        print "</li>\n";
    }
    
    close STUDS;
    
    print "</ol>\n";
}

print "</body>\n";
print "</html>\n";