#!/usr/bin/perl -w
#
# © 2014 Cyril Brulebois <kibi@debian.org>
#   This program is free software; you can redistribute it and/or
#   modify it under the terms of the Do What The Fuck You Want To
#   Public License, Version 2, as published by Sam Hocevar. See
#   http://sam.zoy.org/projects/COPYING.WTFPL for more details.

use strict;
use Email::Filter;
use File::Basename;
use File::Copy;
use File::Slurp;

# No nested maildirs:
my $mails = $ENV{HOME} . "/mails";

# Apparently Message-ID shouldn't be trusted, let's try a given header
# combination instead:
sub get_hash_from_file {
  my $file = shift;
  my $m = Email::Filter->new(data => scalar read_file($file));
  return join "###", map { $m->header($_) } qw(From Subject Date);
}

# Reference hash, mail piped from mutt:
my $ref_hash = get_hash_from_file(\*STDIN);

# Walk maildirs, checking new mails, and comparing hash:
my $found = 0;
for my $maildir (<$mails/*>) {
  for my $newmail (<$maildir/new/*>) {
    if (get_hash_from_file($newmail) eq $ref_hash) {
      $found++;
      print "found in " . basename("$maildir"). "\n";
      # Move, making sure ',S' is present for mutt to consider it read
      # and not just old:
      (my $readmail = basename $newmail) =~ s/,$/,S/;
      move($newmail, "$maildir/cur/$readmail")
        or print "  unable to mark as read";
    }
  }
}

# Let caller have a look:
print "=> $found occurrences\n";
sleep 1;
