#!/usr/bin/perl -w
#
# checkQuotas.pl
# prints out accounts with mail storage size close to or over quota.
#
# 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';

my $threshold=90; # report if account is 90% full

#### 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";


#processFile('accountList.txt');
#processAccount("t1");
#processDomain("company.com");
processAllDomains();


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

sub processFile {
  my ($fname)=@_;
  open(FILE,$fname) || die "can't open $fname: $!\n";
  while(<FILE>) {
    chomp;
    next if(/^#/);
    my $account=$_;
    if(length($account)>3) {
      processAccount($account);
    }
  }
  close(FILE);
}

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 $data=$cli->GetAccountEffectiveSettings($account);
  unless($data) {
    print "*** Can't get settings for $account:".$cli->getErrMessage."\n";
    return;
  }
  my $quota=$data->{MaxAccountSize};
  return if($quota eq 'unlimited');
  my $quota0=$quota;
  if($quota=~/(\d+)G/) {
    $quota=$1*1024*1024*1024;
  }elsif($quota=~/(\d+)M/) {
    $quota=$1*1024*1024;
  }elsif($quota=~/(\d+)K/) {
    $quota=$1*1024;
  }
  
  my $size=$cli->GetAccountInfo($account,'StorageUsed');

  if($size*100/$threshold > $quota) {
    print "$account\t$size\t$quota0\t(".int($size*100/$quota)."%)\n";
  }

  
  
}

__END__

