#!/usr/bin/perl -s
BEGIN { unshift @INC, "$ENV{'HOME'}/perl",
		      "$ENV{'HOME'}/libp/perl", "$ENV{'HOME'}/lib/perl" }

$longlen  = 77;
$txt2html = 'webrowse -mqnok 0';

# attach - convert the given text mail msg to MIME plus the given attachments
# Steve Kinzler, steve@kinzler.com, Jan 03
# https://kinzler.com/me/home.html#unix

$usage = "usage: $0 [ - | mail_file ] [ -m ] [ attachment_file[//ext] ... ]
	-m	attach a marked-up HTML alternative to the mail text body
Attachment filenames may be appended with double-slashes and an extension
to specify their MIME type, if necessary.\n";
die $usage if $h;

use MIME::Entity;
use MIME::Types;
$types = MIME::Types->new;

@argv = @ARGV;
@ARGV = (shift @argv) || ('-');

shift(@argv), $m = 1 if $argv[0] eq '-m';

while (<>) {
	last if /^\s*$/;
	print;
}

$long = 0; @body = ();
unless (eof) {
	while (<>) {
		$long++ if length >= $longlen;
		push(@body, $_);
	}
}

if (! @body) {
	$entity = MIME::Entity->build(Type => 'multipart/mixed');

} elsif (! $m) {
	$entity = MIME::Entity->build(
		Type	 => $types->mimeTypeOf('txt')->type,
		Encoding => ($long) ? 'quoted-printable' : -SUGGEST,
		Data	 => \@body);

} else {
	$entity = MIME::Entity->build(Type => 'multipart/alternative');
	$entity->attach(
		Type	 => $types->mimeTypeOf('txt')->type,
		Encoding => ($long) ? 'quoted-printable' : -SUGGEST,
		Data	 => \@body);

	$| = 1;
	if (open(MARKUP, '-|')) {
		$html = join('', <MARKUP>);
		close MARKUP;
		$html =~ s/<title\b[^>]*>.*?<\/title>\s*//is;
		$html =~ s/<base\b[^>]*>\s*//is;
	} else {
		open(TXT2HTML, "| $txt2html") || exit;
		print TXT2HTML @body;
		close TXT2HTML;
		exit;
	}
	print(STDERR "$0: markup failure, not attaching HTML alternative\n")
						if $html eq '';
	$entity->attach(Type     => $types->mimeTypeOf('html')->type,
			Encoding => 'quoted-printable',
			Data     => $html)	if $html ne '';

	if (@argv) {
		$e = MIME::Entity->build(Type => 'multipart/mixed');
		$e->add_part($entity);
		$entity = $e; undef $e;
	}
}

foreach (@argv) {
	print(STDERR "$0: skipping directory ($_)\n"), next if -d;

	s/\/\/([^.\/]*)$// || /[^\/]\.([^.\/]*)\/?$/;
	$ext = ($1 ne '') ? $1 : (-B _) ? 'exe' : 'txt';

	$entity->attach(Path	    => $_,
			Type	    => $types->mimeTypeOf($ext)->type,
			Disposition => 'attachment',
		        Encoding    => -SUGGEST);
}

$entity->print;
