#!/usr/bin/perl -w
#
# countMailboxMessages.pl
#
# This script prints out the number of messages in each mailbox
#
# Please mail your comments and suggestions to <support@old.communigatepro.ru>

use strict;
use CLI;  #get one from old.communigatepro.ru/CGPerl/
use Data::Dumper;

####  YOU SHOLD REDEFINE THESE VARIABLES !!!

my $CGServerAddress='127.0.0.1';  #IP or domain name;
my $Login='postmaster';
my $Password='pass';

#### end of the customizeable variables list



my $cli = new CGP::CLI( { PeerAddr => $CGServerAddress,
                          PeerPort => 106,
                          login    => $Login,
                          password => $Password } )
   || die "*** Can't login to CGPro CLI: ".$CGP::ERR_STRING."\n";

my ($nAccounts,$nMailboxesTotal,$nMessagesTotal)=(0,0,0);


#processDomain("company.com");
processAllDomains();

print "\n\nAccounts total: $nAccounts\n";
print "Mailboxes total: $nMailboxesTotal\n";
print "Messages total: $nMessagesTotal\n";

print ".\n";
$cli->Logout();
exit;


sub processAllDomains {
  my $DomainList = $cli->ListDomains()
               || die "*** Can't get the domain list: ".$cli->getErrMessage.", quitting";
  foreach(@$DomainList) {
    processDomain($_);
  }
}         

sub processDomain {
  my $domain=$_[0];
  print "Domain: $domain\n";

  my $cookie="";
  do {
    my $data=$cli->ListDomainObjects($domain,5000,undef,'ACCOUNTS',$cookie);
    unless($data) {
      print "*** Can't get accounts for $domain: ".$cli->getErrMessage."\n";
      return;
    }
    $cookie=$data->[4];
    foreach(keys %{$data->[1]} ) {
      processAccount("$_\@$domain"); 
    }
  }while($cookie ne '');
 
}

sub processAccount {
  my $account=$_[0];
  print "  Account: $account\n";

  my ($nMailboxes,$nMessages)=(0,0);
  
  my $mailboxesList=$cli->ListMailboxes(accountName=>$account);  
  unless($mailboxesList) {
    print "*** Can't list mailboxes for $account:".$cli->getErrMessage."\n";
    return;
  }
  foreach(sort keys %$mailboxesList) {
    my $data=@$mailboxesList{$_};
    if(ref $data eq 'ARRAY') {
      $data=@$data[0];
    }   
    if(ref $data eq 'HASH') {
   
 #     if(!$data->{Class} || $data->{Class}!~/^IPF\./) {
      {
        $nMailboxes++;
        my $nMsg=$data->{Messages} || 0;
        $nMsg=~s/^#//;
        print "    $_: $nMsg\n";
        $nMessages+=$nMsg;
      }
    }
  }
  print "  $account\tMailboxes:$nMailboxes\tMessages:$nMessages\n";
  $nMailboxesTotal+=$nMailboxes;  
  $nMessagesTotal+=$nMessages;  
  $nAccounts++;
}

__END__

