#! /usr/bin/perl -T

# A simple script to test the CGI interface.

my $dir;
BEGIN {
    use Cwd qw(abs_path);
    $dir = abs_path(__FILE__);
    $dir =~ /(.*)(\/.*\/.*\/.*\..*)$/;
    $dir = $1;
    unshift(@INC, $dir . "/lib");
}

use strict;
use warnings;
use utf8;
use CGI qw(:standard -utf8);

use HTMLGenerator qw(error_page);

# STDIN must NOT be set to binmode "UTF-8", since CGI with the '-utf8'
# flag handles this.
binmode( STDOUT, "utf8" );
binmode( STDERR, "utf8" );

$ENV{PATH} = ""; # Untaint and clean PATH

my $cgi = new CGI;
my %params = $cgi->Vars;

eval {
    my $date = `/bin/date`;
    chomp $date;

    if( ! $date ) {
        die "No date receved from the system";
    }

    my $abs_path = abs_path(__FILE__);
    my $inc_path = join( "<br />", @INC );
    
    my $html;

    $html = $cgi->header(-type=>"text/html", -expires=>'now', -charset=>'UTF-8');

    my $keys = join( ", ", keys %params ); 
    my $values = join( ", ", values %params );
   
    $html .= <<EOF;
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
        <title>
          Saulius Gražulis
        </title>
      </head>
      <body>
        <h1>Test -- Saulius Gražulis</h1>
        <p>This is a simple CGI test</p>
        <p>I am run in the directory $abs_path</p>
        <p>My Perl \@INC path is:<br />$inc_path</p>
        <p>Run at $date from $ENV{REMOTE_ADDR}</p>
        <p>Document Root = $ENV{DOCUMENT_ROOT}</p>
        <p>Request URI = $ENV{REQUEST_URI}</p>
        <p>Received QUERY_STRING=$ENV{QUERY_STRING}</p>
        <p>The CGI module returned:<br />
          keys = $keys<br />
          values = $values<br />
        </p>

        <h2>All environment variables:</h2>

EOF

    for my $key (sort keys %ENV) {
        $html .= " " x 8 .
            $key . ": " .
            $ENV{$key} . "<br />\n"
    }

    $html .= <<EOF;
        <p align="right">
          <a href="https://validator.w3.org/check?uri=referer">
            <img border="0"
                 src="https://www.w3.org/Icons/valid-html40"
                 alt="Valid HTML 4.0!" height="31" width="88">
          </a>
        </p>

      </body>
    </html>
EOF

    print $html;
};

if( $@ ) {
    error_page( $cgi, $@ );
}
