#!/usr/bin/perl

use strict;
use warnings;
use Email::MIME;
use Email::Sender::Simple qw(sendmail);
use IO::All;

my $parsed = Email::MIME->new(join('', <STDIN>));
my @parts = $parsed->parts;

my $docfilename = 'remarkable.docx';
my $docfile = "/tmp/$docfilename";
my $tmpfile = '/tmp/converttmp';

unlink $docfile if -e $docfile;
unlink $tmpfile if -e $tmpfile;

foreach my $p (@parts) {
	if ($p->content_type =~ "^text/html.*") {
		open(my $fh, '>', $tmpfile) or die "Could not open $tmpfile $!";
		print $fh $p->body;
		close $fh;
		`pandoc -f html -t docx -o $docfile $tmpfile`;
	}
}

# multipart message
my @sparts = (
	Email::MIME->create(
		attributes => {
			content_type => "text/plain",
			disposition  => "inline",
			encoding     => 'quoted-printable',
			charset      => 'utf-8',
		},
		body_str => "Ja està !  Fitxer convertit a Word.\n",
	),
	Email::MIME->create(
		attributes => {
			filename     => "$docfilename",
			content_type => "application/octet-stream",
			disposition  => "attachment",
			encoding     => "base64",
			name         => "$docfilename",
		},
		body => io( "$docfile" )->binary->all,
	),
);
$sparts[1]->encoding_set('base64');

my $email = Email::MIME->create(
	header_str => [
		From    => 'conversion@example.com',
		To      => [ 'destination@example.com' ],
		Subject => 'Fitxer convertit.',
	],
	parts       => [ @sparts ],
);

sendmail($email);
