#!/usr/bin/perl

use MIME::Parser;
use Data::Dumper;
use File::Path;
use File::Temp;
use Getopt::Std;

use strict;
use warnings;

my $version = 0.4;
my @viewer_cmd = qw(htmail-view -m);

# getopt stuff
$Getopt::Std::STANDARD_HELP_VERSION++;

sub HELP_MESSAGE {
    print <<USG;
Usage:

  htmail-decode [-v]

    -v		be more verbose

    --help      show this help
    --version   show version information

    The raw mail is read from STDIN.

USG
}

sub VERSION_MESSAGE {
    print <<LIC;

 htmail-view $version - single web page renderer based on WebKit

 Authors:
   Thomas Liske <thomas\@fiasko-nw.net>

 Copyright Holder:
   2015 (C) Thomas Liske [http://fiasko-nw.net/~thomas/]

Upstream:
  https://github.com/liske/htmail-view

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

LIC
#/
}

our $opt_v;
unless(getopts('v') && (scalar @ARGV) != -1) {
    HELP_MESSAGE;
    exit 1;
}

push(@viewer_cmd, '-v') if($opt_v);

my $dir = File::Temp->newdir;
my $parser = new MIME::Parser;
$parser->output_under($dir);

my $mail = $parser->parse(\*STDIN);

unless($mail->is_multipart) {
    print STDERR 'ERROR: Unexpected MIME type '.$mail->effective_type."!\n";
    exit 1;
}

my %cids;
sub find_cid {
    my $part = shift;
    my $cid;

    if($part->is_multipart) {
	for my $sub ($part->parts) {
	    find_cid($sub);
	}
    }
    elsif($cid = $part->head->mime_attr('content-id')) {
	$cid =~ s/(^<|>$)//g;
	$cids{$cid} = 'file://'.$part->bodyhandle->path;
	print STDERR "FINDCID#CIDREF $cid => $cids{$cid}\n" if($opt_v);
    }
}

sub find_htmail {
    my $part = shift;

    if($part->effective_type eq 'text/html') {
	my $pid = open(HPIPE, '|-');
	unless(defined($pid)) {
	    print STDERR "ERROR: Failed to fork: $!\n";
	    exit 2;
	}

	if($pid) {
	    print HPIPE join("\n", %cids, '');
	    close(HPIPE);
	}
	else {
	    print STDERR "TXTHTML#VIEWER ".join(' ', @viewer_cmd, 'file://'.$part->bodyhandle->path)." \n" if($opt_v);
	    unless(exec(@viewer_cmd, 'file://'.$part->bodyhandle->path)) {
		print STDERR "ERROR: Failed to run 'htmail-view': $!\n";
		exit 3;
	    }
	}

	print STDERR "Waiting for HTMaiL-Viewer to return...\n\n";
	waitpid($pid, 0);

	exit 0;
    }
    elsif($part->is_multipart) {
	for my $sub ($part->parts) {
	    find_htmail($sub);
	}
    }
}

find_cid($mail);
find_htmail($mail);
