#!/usr/bin/perl
#
# Wolfgang Rosner, wrosner@tirnet.de
# oct 2016
# try to extract header and HTML from claws mail files
# and pipe them to pdf generator
# preliminary draft
# don't expect anything serious from this hack
# - only errors and bullshit -


use strict;
use warnings;
use Email::MIME;
# use Email::Simple;
use Data::Dumper;
use HTML::Escape;

# ======== some config here: ===========

# list of headers to print
my @headlist = qw(From To cc bcc Date Subject);

# find your favourite pdf viewer
my $pdfviewer = `which okular` or die ("pdfviewer not found");

my $wh2p = `which wkhtmltopdf` or die ("wkhtmltopdf not installed");

# ============= end of config - no user change below =============

# read message from STDIN
my $message = "";
while (<>) {
  $message .= $_
}

print "### reading done ###\n";


my $parsed = Email::MIME->new($message);

my @parts = $parsed->parts; # These will be Email::MIME objects, too.
# my $decoded = $parsed->body;
# my $non_decoded = $parsed->body_raw;

my $content_type = $parsed->content_type;


printf "## parsing done ##\n";
printf "content-type: %s \n", $content_type ;

print "=== debug structure: ===\n";
print $parsed->debug_structure;
print $parsed->header;
print "=====================\n";


# collect header lines according to configured @headlist
my @hl_str = ();
my $headitem;
foreach  $headitem (@headlist) {

  my @headtxl = $parsed->header($headitem) ;
  my $htlitem ;
  foreach $htlitem ( @headtxl) {
    printf "header %s == %s\n",$headitem, $htlitem;
    push @hl_str , sprintf ("%s: %s", $headitem, $htlitem) ;
  }

}

print Dumper ( \@hl_str);

# produce some basic html
my $htmlheadstr  = "&nbsp;<br>&nbsp;<hr>&nbsp;<br>&nbsp;\n";
my $htmlheadstr .= "<font size=\"4\"><b>";
my $headerline; 

# with the header lines 
foreach $headerline (@hl_str) {
  $htmlheadstr .= escape_html($headerline) ;
  $htmlheadstr .= "<br>\n";
}

$htmlheadstr .= "</br></font>";
$htmlheadstr .= "<br><hr><br>\n";

# print $htmlheadstr ;

print "### search for HTML part ###\n";

my $body = $parsed->body ;

my $part;
foreach $part ( @parts) {
  my $ct = $part->content_type;
  printf("content type = %s \n",  $ct);

  if ($ct =~ /^text\/html/ ) {
    # print "TREFFER \n";
    $body = $part->body;
    last;
  }
  # print "~~~~~~~~~~~~~~~~~~~~~~~~ \n";
}

# print "~~ body: ~~~~~~~~~~~~~~~~~~~~~~ \n";
# print $body;
# die (" we have a body");

# pipe the stuff through converter to viewer
if ($body) {

  # my $pid = open(PDFPIPE, "| wkhtmltopdf - - | okular -  ") or die "Couldn't fork: $!\n";
  my $pid = open(PDFPIPE, "| wkhtmltopdf - - | okular - 2>/dev/null ") or die "Couldn't fork: $!\n";

  print PDFPIPE $htmlheadstr ;
  print PDFPIPE $body ;

  close(PDFPIPE) or die "Couldn't close: $!\n";
  
}

