#!/usr/bin/perl

use warnings;
use strict;
use LWP::UserAgent;
use CGI qw(-utf8);
use CGI::Carp qw(fatalsToBrowser);
use Net::SCP;
use Template;
use FindBin qw($RealBin);

my $cgi = new CGI;
my $tt = Template->new({INCLUDE_PATH => "$RealBin/../templates/"})
   or die "Can't create template object: $Template::ERROR\n";

if (!$cgi->param("_submit")) {

   print CGI::header(-type => "text/html", -charset => "utf-8");

   $tt->process("status.html");
   exit 0;
}
my $id=$cgi->param("anummer");
chomp $id;
my @uuid;
open (UUID, "<UUID");
   @uuid = <UUID>;
close UUID;
my $uuid = join(" .:;:. ",@uuid);
my ($error, $farbe, $aerror);
if ($id eq ''){
   $error="missing Key";
   $farbe='rot';
}
else{$farbe="black"}
if($id !~ m/^[A-F0-9]{8}\-[A-F0-9]{4}\-[A-F0-9]{4}\-[A-F0-9]{4}\-[A-F0-9]{12}/){
   $error="invalid Key";
   $farbe="red";
   $aerror="Format: 1A2B3C4B-5E6F-7G8H-9I0J-1K2L3M4N5O6P";

}

if ($id =~ m/^[A-F0-9]{8}\-[A-F0-9]{4}\-[A-F0-9]{4}\-[A-F0-9]{4}\-[A-F0-9]{12}/){
   for(my $x=0;$x<=$#uuid;$x++){
      chomp($uuid[$x]);
      if ($id eq $uuid[$x]) {
         $farbe="black";
         $error='';
         if (-e "/var/www/tmp/$id"){
            last;
         }
         else{$error="Your order will be processed";}
         my $url='http://192.168.0.144/cgi-bin/scp';
         my $ua=LWP::UserAgent->new;
         my $req=HTTP::Request->new("POST",$url);
         $req->content("id=$id");
         $ua->request($req);
         last;
      }
      else {$error="No such ID";}
   }
}

if ($error){
   print CGI::header(-type => "text/html", -charset => "utf-8");
   $tt->process("status.html", {
         farbe => $farbe,
         anummer => $id,
         error => $error,
         aerror => $aerror,
         test => $uuid,
      }) or die $tt->error();
   exit 0;
}
print CGI::header(-type => "text/html", -charset => "utf-8");
$tt->process("download.html",{
      uuid => $id,
})or die $tt->error;
exit 0;
__END__
