#!/usr/bin/perl
use strict;
use warnings;

my %cgi = ();

$|=1;
#look at what the user set to us in the URL
my $query=$ENV{QUERY_STRING};
#POST data over writes what came in on the URL
read(STDIN, $query, $ENV{'CONTENT_LENGTH'}) if ($ENV{'CONTENT_LENGTH'} > 0);
my @q=split(/&/,$query);

foreach (sort(@q)) {
	my ($name, $value) = split(/=/, $_);

	$name  =~ tr/+/ /;      # a space used to be encoded as a plus
	$value =~ tr/+/ /;
	# get rid of the hex we were sent
	$name  =~ s/%([A-F0-9][A-F0-9])/pack("C", hex($1))/gie;
	$value =~ s/%([A-F0-9][A-F0-9])/pack("C", hex($1))/gie;
	$cgi{$name}=$value;     # $cgi_ has xss unfriendly values
				# the following are to to stop cross site scripting but
				# they make it hard to check for & < > ( or ) in values
	$value =~ s/&/&amp;/gi;
	$value =~ s/>/&gt;/gi;
	$value =~ s/</&lt;/gi;
	$value =~ s/\(/&#40;/gi;
	$value =~ s/\)/&#41;/gi;
	$cgi{$name}=$value;
}

if ( $cgi{reg} !~ /^[A-Za-z]{3}$/ ) {
  $cgi{reg} = "";
} else {
  $cgi{reg} =~ tr/a-z/A-Z/;
}


### Print out the lookup form...
print <<EOF;
Cache-Control: no-cache, no-store, must-revalidate\nPragma: no-cache\nExpires: 0\nContent-type:text/html\n\n

<html>
<head>
	<title>Mobile Registration Lookup</title>
</head>
<body>
<form method="post" action="reg.pl">
Registration: VH-<input type="text" value="$cgi{reg}" name="reg" size="3" length="3"><input type="submit" value="Search">
</form>
EOF

open(CSV, "ACRFTREG.CSV");
my $updated = localtime((stat CSV)[9]);
close(CSV);
print "<font size=\"-2\">Database last updated: $updated</font>\n";

## Check the registration if we have it...
if ( $cgi{reg} ) {
	my $string = `grep -e \"^\\\"$cgi{reg}\\\",*\" ACRFTREG.CSV`;
	$string =~ s/"\r\n$//g;
	my @columns = split(/","/, $string);

	print <<EOF;
<hr>
Registration Info for VH-$cgi{reg}<br>
<pre>MANUFACTURER:
$columns[1] $columns[37]
Aircraft Type: $columns[2] ($columns[3])
Year of build: $columns[38]
Serial: $columns[4], ICAO Code: $columns[42], MTOW: $columns[5]kg

ENGINES:
$columns[6] x $columns[7]
$columns[8] $columns[9]
Fuel: $columns[10]

REGISTRATION:
Type: $columns[11]
$columns[12]
$columns[13] $columns[14] $columns[15] $columns[16] $columns[17] $columns[18]
Start: $columns[19]
Expiry: $columns[40]

OPERATOR:
$columns[20]
$columns[21] $columns[22] $columns[23] $columns[25] $columns[26]
$columns[28]
Start: $columns[27]
First Reg: $columns[28]

FEATURES:
Gear: $columns[29]
Airframe: $columns[30]
Catagory: $columns[31] $columns[32]
Prop: $columns[33] $columns[34]
TypeCert: $columns[35]
EOF
}

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

