#!/usr/bin/perl -s

$minhdr	  = 'minhdr -m';
$txt2html = 'webrowse -mqnok 0';

$frmcolor = '#009900';	# header color for sender lines
$to_color = '#999900';	# header color for recipient lines
$datcolor = '#009999';	# header color for date lines
$sbjcolor = '#990099';	# header color for subject lines
$txtcolor = '#DDDDDD';	# background color for text attachments
$attcolor = '#FF0000';	# listing color for unpresented attachments

sub htmlcust {
	return unless ($ENV{'USER'} || $ENV{'LOGNAME'}) eq 'kinzler';

	$dom = 'l\.facebook\.com';
	s!\bhttps?://$dom/+l(/+[^/]+/+|\.php\?u=)([^\s\'"`<>()\[\]{}]*)!
	  $_ = &urldecode($2), s#&amp;h=.*##, m#://# || s#^#http://#, $_!gie;
}

# mimeindex - create a msg-index.html file in the given directories
# Steve Kinzler, steve@kinzler.com, Oct 05
# https://kinzler.com/me/home.html#unix

$usage = "usage: $0 directory ...\n";
die $usage if $h || ! @ARGV;

$mbxre = 'mimebrowse|mbx-\d+-\d';
$txtre = 'txt|html?';
$imgre = 'gif|jpe?g|png|bmp';

chop($wd = `pwd`);
foreach $dir (@ARGV) {
	warn("$0: cannot chdir $dir ($!)\n"),
		chdir($wd), next unless chdir($dir);
	warn("$0: cannot opendir $dir/. ($!)\n"),
		chdir($wd), next unless opendir(DIR, '.');
	warn("$0: cannot open $dir/msg-index.html ($!)\n"), close DIR,
		chdir($wd), next unless open(INDEX, '>msg-index.html');
	select INDEX;

	@files = sort readdir DIR; close DIR;

	$hdrs = $subj = '';
	foreach (grep(/^($mbxre)/, @files)) {
		warn("$0: cannot run $minhdr ($!)\n"), next unless
			open(HDR, "$minhdr " . &shencode($_) . '|');
		$hdrs .= '<P><B>' . &ahref($_) . '</B>';
		while (<HDR>) {
			chop;
			last if /^$/;
			$_ = &htmlencode($_);
			s/^\s+/'&nbsp;' x 8/e;
			s/^[-\w]*:/<B>$&<\/B>/;
			s/^<B>From:.*/&color($frmcolor, $&)/ei;
			s/^<B>(To|Cc|Bcc):.*/&color($to_color, $&)/ei;
			s/^<B>Date:.*/&color($datcolor, $&)/ei;
			s/^<B>Subject:.*/&color($sbjcolor, $&)/ei &&
				($subj = $&);
			$hdrs .= "<BR>\n$_";
		}
		$hdrs .= "</P>\n\n";
		close HDR;
	}

	$subj =~ s/^\S*\s*//; $subj =~ s/\s*$//;
	$subj .= ' - ' if $subj ne '';
	chop($cwd = &htmlencode(`pwd`));
	print <<EOF, "\n";
<HTML><HEAD>
<TITLE>${subj}mimeindex - $cwd</TITLE>
</HEAD><BODY>
EOF

	print $hdrs;

	print '<P><PRE>';
	foreach (`ls -al`) {
		s/( (?:\w\w\w +|\d+-\d+-)\d+ +\d+:\d+ )(.*)/$1 . &ahref($2)/e;
		s/.*/&color($attcolor, "<B>$&<\/B>")/e
			unless $2 =~ /^(\.{0,2}$|$mbxre|cid-)/
			    || $2 =~ /\.($txtre|$imgre)$/i;
		print;
	}
	print "</PRE></P>\n\n";

	foreach (reverse grep(/\.($txtre)$/i, @files)) {
		if (/\.txt$/i) {
			print '<P><TABLE><TR><TD><B>', &ahref($_),
			      "</B></TD></TR><TR>\n<TD bgcolor=\"$txtcolor\">";
			warn("$0: cannot run $txt2html ($!)\n") unless
			    open(TXT, "$txt2html < " . &shencode($_) . '|');
			while (<TXT>) { print }
			close TXT;
			print "</TD></TR></TABLE></P>\n\n";
		} else {
			next if /\bmsg-index\b/i;
			print '<TABLE WIDTH="100%"><TR><TD><B>', &ahref($_),
			      "</B></TD></TR></TABLE>\n<HR NOSHADE SIZE=5>\n";
			warn("$0: cannot run cat ($!)\n") unless
			    open(HTML, "cat < " . &shencode($_) . '|');
			while (<HTML>) {
				s/\b((src|href)\s*=\s*['"]?cid):/$1-/gi;
				&htmlcust() if defined &htmlcust;
				print;
			}
			close HTML;
			print "<HR NOSHADE SIZE=5>\n\n";
		}
	}

	foreach (grep(/\.($imgre)$/i, @files)) {
		$url = &urlencode($_);
		print "<P><A HREF=\"$url\"><B>", &htmlencode($_), "</B>\n",
		      "<IMG SRC=\"$url\" BORDER=0 ALIGN=\"TOP\"></A></P>\n\n";
	}

	print "</BODY></HTML>\n";

	close INDEX;
	chdir($wd);
}

## Subroutines ################################################################

sub ahref {
	local($_) = join('', @_);
	'<A HREF="' . &urlencode($_) . '">' . &htmlencode($_) . '</A>';
}

sub color {
	local($c) = shift;
	local($_) = join('', @_);
	"<FONT COLOR=\"$c\">$_</FONT>";
}

sub urlencode {
	local($_) = join('', @_);
	s/[^ \w!\$'()*,\-.]/sprintf('%%%02x', ord $&)/ge;
#	s/ /+/g;
	$_;
}

sub urldecode {
	local($_) = join('', @_);
	s/\+/ /g; s/%([\da-f]{2})/pack('C', hex $1)/gie;
	$_;
}

sub htmlencode {
        local($_) = join('', @_);
        s/&/&amp;/g; s/</&lt;/g; s/>/&gt;/g; s/"/&quot;/g;
        $_;
}

sub shencode {
	local($_) = join('', @_);
	s/'/'\\''/g; s/^/'/; s/$/'/;
	$_;
}
