#!/usr/bin/perl
# tnef -> mime converter, v0.1
# alex pleiner <alex@zeitform.de>
# 2006, use under terms of GPL
#
# usage:
#   cat message | tnefprocess.pl > output
#
# or within .procmailrc
#   :0HB fw
#   * ^Content-Type:.*application/ms-tnef
#   | tnefprocess.pl

# I merged and changed the following scripts:
# killtnef.pl -  http://cpan.online.bg/authors/id/H/HI/HIGHTOWE/killtnef-1.0.2.pl
# ytnefprocess.pl - http://ytnef.sourceforge.net

# while ytnefprocess uses system calls to ytnef, killtnef can not handle tnefs
# nested deeply within the mime structure
# This script is pure perl and handles nested mime structures (tnef within fwd)

# Attention: this script will not remove winmail.dat, but add its contents as
# additional attachments to the same level.

use strict;
use MIME::Parser;
use Convert::TNEF;
use MIME::Types;

my $mimetypes = MIME::Types->new;
my $parser = MIME::Parser->new;
our $entity = $parser->parse ( \*STDIN );

processParts($entity); ## do the work

$entity->sync_headers(Length=>'COMPUTE');
$entity->print( \*STDOUT );
$entity->purge;

sub processParts
  {
    my $entity = shift;

    ## multipart
    if ($entity->parts)
      {
        foreach my $part ( $entity->parts ) { processParts($part); }
      }

    ## tnef
    elsif ( $entity->mime_type =~ /ms-tnef/i )
      {

	## Create a tnef object
	my %TnefOpts=('output_to_core' => '4194304', 'output_dir' => '/tmp');
	my $tnef = Convert::TNEF->read_ent($entity, \%TnefOpts);
	unless ($tnef)
	  {
	    warn "TNEF CONVERT DID NOT WORK: " . $Convert::TNEF::errstr . "\n";
	    return;
	  }
	
	## iterate tnef parts and attach
	foreach ($tnef->attachments)
	  {
	    my ($ext) = ($_->longname =~ /\.([A-Za-z]{2,4})$/);
	    my $type = $mimetypes->mimeTypeOf($ext) || "application/octet-stream";
	    my $disposition = "attachment"; # might switch to inline for some mimetypes

	    $entity->attach(
			    Filename    => $_->longname,
			    Type        => $type,
			    Disposition => $disposition,
			    Encoding    => "-SUGGEST",
			    Data        => $_->data,
			    Top         => 0,
			   );
	  }

	$tnef->purge;

      }
  }

#eof

