#!/usr/bin/perl
# 
# Copyright (c) 2008 by Nic Bernstein
# for Onlight, llc, Milwaukee, WI  53202
# Thu May 15 16:32:02 CDT 2008
#
# All Rights Reserved
#
# cyrus_get_quota.pl - a script to read the cyrus IMAP quotas and
# produce an LDIF file suitable to be imported into a directory
# to be used with  the cyrus_ldap_quota.pl script

# Load libraries
use Cyrus::IMAP::Admin;
use Net::LDAP qw(:all);
use Net::LDAP::Util qw(ldap_error_desc);
use Unix::Syslog qw(:macros);  # Syslog macros
use Unix::Syslog qw(:subs);    # Syslog functions

# Open syslog connection
openlog( "cyrus_get_quota.pl", LOG_PID, LOG_LOCAL4 );
syslog LOG_INFO, "Begining run...";

# Read our configuration information
require ( '/etc/cyrus-utils.conf' );

# These shouldn't have to change
my $counter = 0;

# Create IMAP object
$imap_client = Cyrus::IMAP::Admin->new($imap_host)
        or syslog LOG_ERR, "Can't connect to IMAP server: $@";

$imap_client->send(undef, undef, "LOGIN %s %s", $imap_user, $imap_pw)
        or syslog LOG_ERR, "could not send user:pass to the server: $!";

# Create LDAP object
$ldap_client = new Net::LDAP ( $ldap_host, port => $ldap_port, )
        or syslog LOG_ERR, "can't make new LDAP object: $@";

# Bind to the LDAP server as administrator
$mesg = $ldap_client->bind ( $bind_dn, password => $bind_pw );
syslog LOG_WARN, "Failed to bind to %s as %s: %s", $ldap_host, $bind_dn,
                                    ldap_error_desc( $mesg ) if $mesg->code;

# perform search for usernames
$search_result = $ldap_client->search( base   => $base_dn, scope  => 'one',
                                       filter => $ldap_user_filter );
syslog LOG_INFO, "Username search failed for: %s",
                  ldap_error_desc( $search_result ) if $search_result->code;

# process each user in the directory
$count = 0;
while ( $entry = $search_result->shift_entry )
{   
    $user = $entry->get_value( $ldap_user_attr );
    $mailbox = $imap_prefix . $delimiter . $user;
    syslog LOG_INFO, "Quota for $user is $quota[1][1]" if
                      @quota = $imap_client->quota( $mailbox )
                      or syslog LOG_ERR, "could not get quota for $mailbox: $!";

    # Now poop out an ldif fragment on sdtout
    printf ("dn: %s\n", $entry->dn( ));
    print ("changeType: modify\n");
    print ("add: objectClass\n");
    print ("objectClass: inetMailUser\n");
    print ("-\n");
    print ("add: inetMailUserVersion\n");
    print ("inetMailUserVersion: 1\n");
    if ($quota[1][1] > 0) {
        print ("-\n");
        print ("add: mailQuota\n");
        printf ("mailQuota: %s\n", $quota[1][1]);
        print ("\n");
    }
    $count++;
}

# Close the LDAP connection
$ldap_client->unbind();
$ldap_client->disconnect();

# There is no IMAP LOGOUT method, so destroy the object...
Cyrus::IMAP::Admin::DESTROY ($imap_client);

# Log the end of our run
syslog LOG_INFO, "Ending run, updated $count quota records.";
1;

