#!/usr/bin/perl -w

#----------------------------------------------------------------------
# copyright (C) 1999-2005 Mitel Networks Corporation
# Copyright (C) 2006 Gordon Rowell <gordonr@gormand.com.au>
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# 		
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 		
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
#----------------------------------------------------------------------
use strict;

use esmith::AccountsDB;
use User::pwent;
use File::Find;
use Mail::Header;

use constant VERBOSE => 0;

my %delivered2;

my $adb = esmith::AccountsDB->open;

die "Couldn't open AccountsDB\n" unless $adb;

my @users = ('admin', map { $_->key } $adb->users);

foreach my $user ( @users )
{
    my $pwent = getpwnam($user) 
	or die "Couldn't get password entry for $user\n";

    find({ wanted => \&wanted}, $pwent->dir . "/Maildir");
}

for my $key (sort keys %delivered2)
{
    print "$key: $delivered2{$key}\n";
}

sub wanted
{
    return unless -f;
 
    my $name = $File::Find::name;

    unless ($name =~ /(\d+\.\S+)/)
    {
	warn "Unknown filename $name\n" if VERBOSE;
	return;
    }

    $name = $1;

    open (FILE, $name) or die "Couldn't open $name\n";

    my $header = new Mail::Header \*FILE;

    unless ($header)
    {
	warn "Couldn't create Mail::Header object";
	next;
    }

    for ($header->get("Delivered-To"))
    {
	chomp;
	next if /^alias-localdelivery/;
	$delivered2{lc($_)}++;
    }
}
