#!/usr/bin/perl
use strict;

use Cwd;
use Email::Stuffer;
use Net::SMTP;
use WWW::Mechanize ();

my $URL = 'https://schule-infoportal.de';
my $username = $ENV{LOGNAME} || $ENV{USER} || getpwuid($<);
my $emailaddr = $username.'@localhost';

our $logname = "";
our $passwd = "";
my $config_path = getcwd;
die "$config_path/.mjs-portal is missing" unless (-f "$config_path/.mjs-portal");
require "$config_path/.mjs-portal";
# In dieser Datei werden die Variablen $logname und $passwd für den Portallogin belegt

my $ua = WWW::Mechanize->new();
#$ua->agent("Mozilla/5.0 (X11; Linux x86_64; rv:102.0)");

# to check request von mitmproxy
#$ua->proxy( [ 'http', 'https' ] => "http://localhost:8081" );
#$ua->ssl_opts( SSL_ca_file => "/home/sparky6/.mitmproxy/mitmproxy-ca-cert.pem" );

print "GET $URL/login/mjsmuc\n";
my $response = $ua->get("$URL/login/mjsmuc");
print "$response->{_rc}\n";

print "POST $URL/login/mjsmuc\n";
$ua->submit_form(
    fields    => {user => $logname, password => $passwd, },
);
print "$response->{_rc}\n";

print "Führe Link aus: Postkorb\n";
$response = $ua->follow_link(text => "Postkorb");
print "$response->{_rc}\n";

my $html = $ua->{content};
$html =~ /class="unread-bubble".*?<a href="([^"]*)/ms;
unless (defined $1) {
	print "Keine neuen Nachrichten\n";
	exit;
}

print "Found: $1\n";
$response = $ua->follow_link(url => "$1");
print "$response->{_rc}\n";
$html = $ua->{content};

# Hier wird die Nachricht zerlegt
# Alles abschneiden bis zum Postkorb
$html =~ s/.*<div class="postkorb">/<div class="postkorb">/ms;
# Header section extrahieren
my $headers = "";
{
	$html =~ /(<section>.*?<\/section>)/ms;
	$headers = $1;
}
# Sender und Subject extrahieren
my $sender = "";
my $subject = "";
{
	$headers =~ /<span>Von:<\/span>(.*?)<\/div>.*<span>Betreff:<\/span>(.*?)<\/div>/ms;
	$sender = $1;
	$subject = $2;
}
# Nachricht extrahieren
my $nachricht = "";
{
	$html =~ /(<div class="message">.*?)<\/section>/ms;
	die "Cannot parse message." unless (defined $1);
	$nachricht = $1;
}
# Anhange extrahieren
my $anhange = "";
{
	$html =~ /(<section class="attachements">.*?<\/section>)/ms;
	$anhange = $1 if (defined $1);
}
my $message = <<HTMLMAIL;
<html><body>
$headers
$nachricht
$anhange
</body></html>
HTMLMAIL

# Die SMTP-Funktionen werfen dies
eval {
	Email::Stuffer->to($emailaddr)
	  ->from('mailer@maxjosefstift.de')
	  ->html_body($message)
	  ->subject("Portalnachricht von $sender: $subject")
	  ->send;
};
if ($@) {
	die "Mailling failed";
}
print "ok.\n";
