#!/usr/local/perl-5.6.0/bin/perl -w
# Originally written by John Klassa
# Modifications by Diego Zamboni:
# - Allow an argument to specify folders to examine
# - Before the unseen messages are shown, creates a copy of it
#   in the sequence "lastunseen", which is used by other commands
#   to act on the unseen sequence, but they really act on the "lastunseen"
#   snapshot, to prevent accidentally removing new unseen messages, for example.

use strict;

$| = 1;

if(@ARGV) {
   foreach (@ARGV) {
      do_folder($_);
   }
}
else {
   open FDR, "$ENV{HOME}/Mail/.folders" or die "$!";
   
   while (<FDR>)
   {
       chomp;
       do_folder($_);
   }
}

close FDR;

sub do_folder {
  local $_=shift;

  if (open INP, "$ENV{HOME}/Mail/$_/.mh_sequences") {
    my @inp=<INP>;
    if (grep(/^unseen: /, @inp)) {
      print "** $_\n";
      system "mark +$_ unseen -sequence prevunseen -add -zero; scan +$_ unseen";
    }
    elsif (grep(/^prevunseen: /, @inp)) {
      system "mark +$_ prevunseen -sequence prevunseen -delete";
    }

    close INP;
  }
}
