#!/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 Cwd;
use FindBin qw($RealBin);
use Data::UUID;

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("index.html");
   exit 0;
}

# formular wurde ausgefuellt, wir muessen es pruefen und evtl. noch mal
# anzeigen

# CHECK

   my (%error, $ffarbe, $ofarbe, $mfarbe, $rfarbe);
   if ($cgi->param("firma") eq ''){
      $error{firma} = "missing company";
      $ffarbe='rot';
   }
   else{$ffarbe='black'}
   if ($cgi->param("mail") eq ''){
      $error{mail}= "missing mail";
      $mfarbe='red';
   }
   elsif ($cgi->param("mail") !~ m/^[a-zA-Z0-9\.-_]*\@\w+\.\w{2,}/){
      $error{mail}="no valid mail";
      $mfarbe='red';
   }
   else{$mfarbe='black'}
   if ($cgi->param("ort") eq ''){
      $error{ort}= "missing city";
      $ofarbe='red';
   }
   else{$ofarbe='black'}
   if ($cgi->param("req") eq ''){
      $error{req}="missing request";
      $rfarbe='red';
   }
   else{$rfarbe='black'}
   if (%error) {
      print CGI::header(-type => "text/html", -charset => "utf-8");
      $tt->process("index.html", {
            dump => $cgi->Dump(),
            now => time(),
            error => \%error,
            firma => $cgi->param("firma"),
            ffarbe=>$ffarbe,
            mail => $cgi->param("mail"),
            mfarbe=>$mfarbe,
            ort => $cgi->param("ort"),
            ofarbe=>$ofarbe,
            req => $cgi->param("req"),
            rfarbe=>$rfarbe,
      }) or die $tt->error();
      exit 0;
   }

# alles ist ok

my ($uid, $url,  $ua,  $ub, $req);

$ub=new Data::UUID;
$uid=$ub->create_str;
open (UUID, ">>UUID") or die "$!\n";
print UUID $uid;
close UUID;
#######################
# Auswerten der Daten #
# des Web-Formulars   #
#######################

my %field = (
      firma => $cgi->param('firma'),
      mail => $cgi->param('mail'),
      ort => $cgi->param('ort'),
      req => $cgi->param('req'),
);

foreach (values %field) {
   s/\&/\<26\>/g;
   s/\=/\<3D\>/g;
   s/\%/\<25\>/g;
   s/\+/\<2B\>/g;
   s/\r\n/\n/g;
}
my $test='test';
open( TEST,"> $test" ) or die "Kann $test nicht öffnen: $!\n";
foreach (sort keys %field) {
   print "$_: $field{$_}\n";
}
close TEST;
my @Feldnamen = $cgi->param();

#######################
# Senden der Daten    #
# via HTTP-POST       #
#######################

$url = 'http://192.168.0.144/cgi-bin/receive';
$ua  = LWP::UserAgent->new;
$ua->env_proxy;
$ua->timeout(20);
$ua->show_progress;
$req = HTTP::Request->new( "POST", $url );
$req->header( 'Content-Type' => 'text/html' );
$req->accept_decodable;
$req->content("ID=$uid&Name=$field{firma}&Mail=$field{mail}&Test=$field{ort}&req=$field{req}");
$ua->request($req);

print CGI::header(-type => "text/html", -charset => "utf-8");
$tt->process("wait.html",{
      uid => $uid
   }) or die $tt->error;

unlink grep { -M > 3/(24*36) } glob("/var/www/tmp/*");

__END__
# Test

open( HTML, ">/var/www/tmp/$uid.html") or die "$!\n";
print HTML ("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html><head><title>Download</title><meta http_equiv=\"refresh\" content=\"10;URL=http://192.168.0.138/tmp/". $uid . "1.html\"></head><script type=\"text/javascript\">
<!--
var homepage = 'http://192.168.0.138/tmp/" . $uid . "1.html';
var sekunden = 10;
function countdownWeiterleitung(){
   sekunden--;
   document.getElementById('counter_span').innerHTML = sekunden;
   if ( !sekunden ) {
      document.location.href = homepage;
   }
}
window.setInterval('countdownWeiterleitung()', 1000);
//-->
</script><body><p>Ihr Download steht in k&uuml;rze bereit!<br>Sie werden in <span id=\"counter_span\" class=\"dd\">10</span> sekunden automatisch Weitergeleitet.<br>Sollte die automatische Weiterleitung nicht funktionieren, klicken Sie bitte <a style=\"text-decoration: none;\" href=\"".$uid."1.html\">hier</a>.</p><p>Bitte beachten Sie, dass Ihr Download nur 5 minuten g&uuml;ltig ist.</p></body></html>");
close HTML;

open( HTML1, $_ = ">/var/www/tmp/$uid" . "1.html" ) or die "$!\n";
print HTML1 ("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html><head><title>Download</title></head><body><p>Klicken Sie bitte auf den Link um ihre Datei zu Downloaden oder anzuzeigen.<br>Zum Speichern des Inhaltes klicken Sie den Link mit der rechten Maustaste an und w&auml;hlen \"Ziel speichern unter...\"</p><p><a style=\"text-decoration: none;\"  href=\"/download/$uid\" type=\"application/octet-stream\">$uid</a></p ></body></html>" );
close HTML1;

#######################
# Erstellen einer     #
# Feedback-Seite zum  #
# Test mit Weiter-    #
# leitung             #
#######################

print $cgi->header('CGI-Feedback'),
  $cgi->start_html(
    -head => $cgi->meta(
        {
            -http_equiv => 'REFRESH',
            -content    => "2;URL=http://192.168.0.138/tmp/$uid.html"
        }
    ),
    -title => 'CGI-Feedback'
  );
$cgi->h1( 'CGI-Feedback vom Programm ', $cgi->i('send') );
foreach my $Feld (@Feldnamen) {
    print $cgi->strong('Feldname: '),
      $Feld,
      $cgi->strong(', Inhalt: '),
      $cgi->param($Feld), "<br>";
}
print $cgi->i($uid), $cgi->end_html;

my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
  localtime(time);
if ( $min >= 55 ) {
    $min += 5;
    $min -= 60;
    $hour += 1;
}
else {
    $min += 5;
}


#foreach my $file (@files) {
#   if (time() - (stat $file)[9] > 300) {
#         unlink $file;
#   }
#   if (-M $file > 3/(24*36)) {
#      unlink $file;
#   }
#}

#open( WRITE, "|sudo at now + 5 minutes" ) or die;
#print WRITE "rm /var/www/$uid*\n";
#print WRITE "rm /var/www/download/$uid*\n";
#close WRITE;


