#!/usr/bin/perl

use warnings;
use strict;
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 ($cgi->param("anummer") eq ''){
   $error="missing Key";
   $farbe='rot';
}
else{$farbe="black"}
if($cgi->param("anummer") !~ 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 ($cgi->param("anummer") =~ 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 ($cgi->param("anummer") eq $uuid[$x]) {
         $farbe="black";
         $error='';
         if (-e "/var/www/download/$id"){
            last;
         }
         else{$error="Your order will be processed";}
         last;
      }
      else {$error="No such ID";}
   }
}

if ($error){
   print CGI::header(-type => "text/html", -charset => "utf-8");
   $tt->process("status.html", {
         farbe => $farbe,
         anummer => $cgi->param("anummer"),
         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__
my $scp=Net::SCP->new();
$scp->scp("root\@192.168.0.144:/var/www/tmp/.$cgi->param('anummer')","/var/www/download/".$cgi->param("anummer"));
