#!/usr/bin/perl

use strict;

my(%headers, %md5sum, $md5sum_res);

my($md5) = "md5sum";
my($md5) = "md5";

my($tmp) = "/tmp/find_body_dupes";

foreach my $fname (@ARGV) {
    unless (open(MSG, $fname)) {
	print(STDERR "couldn't open file '$fname'\n");
    } else {
	my($exit) = 0;
	my($msg_id, $date, $from, $to, $subject);
	while ((my $line = <MSG>) and (!$exit)) {
	    chomp($line);
	    if ($line =~ /^Message-ID: <[^>]+>$/i) {
		$msg_id .= $line;
	    } elsif ($line =~ /^Date:/i) {
		$date .= $line;
	    } elsif ($line =~ /^From:/i) {
		$from .= $line;
	    } elsif ($line =~ /^To:/i) {
		$to .= $line;
	    } elsif ($line =~ /^Subject:/i) {
		$subject .= $line;
	    }
	    $exit = 1 if ($line =~ /^[\r\n]*$/);
	}
	my($fnames) = $headers{"$msg_id\t$date\t$from\t$to\t$subject"};
	if ($fnames) {
#print("$fname: found the same headers in files: '$fnames'\n");
	    unless ($fnames =~ /.\t/) {
		if (open(MSG2, $fnames)) {
		    my($exit2);
		    while ((my $line2 = <MSG2>) and (!$exit2)) {
			$exit2 = 1 if ($line2 =~ /^[\r\n]*$/);
		    }
		    if (open(MD5, ">$tmp")) {
			while (<MSG2>) {
			    print(MD5 $_) unless (/^[\r\n]/);
			}
			close(MD5);
			if (open(MD5SUM, "$md5 $tmp|")) {
			    $md5sum_res = <MD5SUM>;
			    $md5sum_res =~ s/^([\da-f]+)\s+$tmp[\r\n\s]*/$1/;
			    unless ($md5sum{"$msg_id\t$date\t$from\t$to\t$subject\t$md5sum_res"}) {
				$md5sum{"$msg_id\t$date\t$from\t$to\t$subject\t$md5sum_res"} = $fnames;
			    }
			    close(MD5SUM);
			}
		    }
		    close(MSG2);
		}
	    }
	    if (open(MD5, ">$tmp")) {
		while (<MSG>) {
		    print(MD5 $_) unless (/^[\r\n]/);
		}
		close(MD5);
		if (open(MD5SUM, "$md5 $tmp|")) {
		    $md5sum_res = <MD5SUM>;
		    $md5sum_res =~ s/^([\da-f]+)\s+$tmp[\r\n\s]*/$1/;
		    if ($md5sum{"$msg_id\t$date\t$from\t$to\t$subject\t$md5sum_res"}) {
			print ("$fname : ".$md5sum{"$msg_id\t$date\t$from\t$to\t$subject\t$md5sum_res"}."\n");
		    }
		    $md5sum{"$msg_id\t$date\t$from\t$to\t$subject\t$md5sum_res"} .= "\t$fname";
		    close(MD5SUM);
		}
	    }
	}
	$headers{"$msg_id\t$date\t$from\t$to\t$subject"} .= "\t$fname";
	close(MSG);
    }
}
