#!/usr/bin/perl -w

use strict;
use warnings;

my $debug = 0;  # not used, currently.
my $count_new = 0;
my $maildirbase = $ENV{'HOME'} . "/Maildir";
my @hasnew;

sub check_for_new_mail {
    my $folder = shift;
    my $check_unread = shift;
    my $maildir = "$maildirbase/.$folder/";
    my $hash_built = 0;
    if ($check_unread) {
        $hash_built = check_for_new_mail($folder, 0);
	return 1 if (($hash_built) and (not $count_new));
        $maildir .= "cur";
    } else {
	$maildir .= "new";
    }

    if (not opendir DIRH, $maildir) {
	print STDERR "$0: can't open $maildir: $!\n";
    } else {
	my @files = readdir(DIRH);
	closedir(DIRH);

        my $count = 0;

	foreach (@files) {
	    next if (($_ eq '.') or ($_ eq '..'));
            s/,(.*?)$/$1/;
	    if (not /S/) {
		$count++;
		last if not $count_new;
	    }
	}

	if ($count) {
	    my $foldername = ($folder eq '') ? 'INBOX' : $folder;
	    $foldername =~ s/^\.//;
	    $foldername =~ tr/a-z/A-Z/;

	    if ($hash_built) {
		$hasnew[scalar(@hasnew) - 1]{'COUNT'} += $count;
	    } else {
		push @hasnew, { FOLDERNAME => $foldername, COUNT => $count };
	    }

	    return 1;
	}
    }

    return 0;
}


# mainline.

my $do_unread = 0;

foreach (@ARGV) {
    next if not /^--/;
    $debug = 1, next if $_ eq '--debug';
    $count_new = 1, next if $_ eq '--count';
    $do_unread = 1, next if $_ eq '--unread';
    die("$0: Unknown argument [$_].\n");
}

check_for_new_mail('', $do_unread);  # check inbox always.

foreach (@ARGV) {
    next if /^--/;
    check_for_new_mail($_, $do_unread);
}


my $mailtype = (($do_unread) ? "unread" : "new");
my $count = scalar(@hasnew);
if ($count <= 0) {
    print("No $mailtype mail.\n");
} else {
    my $i;
    my $countstr;
    print("You have $mailtype mail in");
    for ($i = 0; $i < $count - 1; $i++) {
	$countstr = (($count_new) ? " ($hasnew[$i]{'COUNT'})" : "");
	print(" $hasnew[$i]{'FOLDERNAME'}$countstr,");
    }
    $countstr = (($count_new) ? " ($hasnew[$i]{'COUNT'})" : "");
    print(" $hasnew[$i]{'FOLDERNAME'}$countstr.\n");
}

# end of newmail.pl ...