#!/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;
}

open (UUID, "<UUID");
my @uuid = <UUID>;
close UUID;

my ($error, $farbe);
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";
}
else{
   foreach (@uuid){
      if ($cgi->param("anummer") eq $_) {
         $farbe="black";
         next;
      }
      else{
         $error="no such Job-ID";
         exit 0;
      }
   }
}
if ($error){
   print CGI::header(-type => "text/html", -charset => "utf-8");
   $tt->process("status.html", {
         farbe => $farbe,
         anummer => $cgi->param("anummer"),
         error => \$error,
      }) or die $tt->error();
   exit 0;
}
my $scp=Net::SCP->new();
$scp->scp("root@192.168.0.144:/usr/lib/cgi-bin/".$cgi->param("anummer"), "/var/www/download/".$cgi->param("anummer"));

print CGI::header(-type => "text/html", -charset => "utf-8");
$tt->process("download.html",{
      uuid => $cgi->param("anummer")
});
