#!/usr/bin/perl
# vim: set tabstop=3 foldmethod=marker:

# Description:
#
# Create a postfix map (to use with relay_recipients_map) from an Active Directory Server
# Just configure the user and password to use for ldap bind.
# Note: you can use any user
# You probably need to edit the $ldap-search line too

# Author: 
# Bruno Bonfils, <asyd@debian-fr.org>
# Antoine Delaporte, <adlp@adlp.org>


# License: BSD, March 2005

use Net::LDAP;
use strict;

my @mail;
my $hostname = 'ldap.asyd.net';
my $binddn = 'cn=mail,ou=robots,ou=people,dc=microsoft,dc=fr';
my $bindpw = '42DTCPWET';
my $basedn = 'ou=People,dc=microsoft,dc=fr';
my $filter = '(&(objectClass=user)(msExchUserAccountControl=0))';

my $filename = 'relay-recipients.txt';

# sub parse_entry {{{

sub parse_entry {
	my $entry = shift;

   my $dn = $entry->dn;

	my @buffer;

	@buffer = $entry->get_value('proxyAddresses');

	foreach my $addr (@buffer) {
		my ($proto, $finaladdr) = split (/:/, $addr);

		push @mail, $finaladdr 
			if ($proto =~ /smtp/i);
	}

	@buffer = $entry->get_value('mail');

	push @mail, @buffer
		if defined @buffer;
}

# }}}
# {{{ sub write_file

sub write_file {
	unlink ($filename);
	open (FH, "> $filename")
		or die "Can't open $filename for writing";

	# Sort the array
	@mail = sort @mail;

	# Remove the duplicate entries
	my $prev;
	@mail = grep($_ ne $prev && (($prev) = $_), @mail);

	foreach (@mail) {
			print FH lc($_), "\t\tOK\n";
	}

	close (FH);
}

# }}}

my $ldaph = Net::LDAP->new($hostname)
   or die "Can't contact to LDAP server $@";

$ldaph->bind($binddn, password => $bindpw)
   or die "Can't bind $@";

my $search = $ldaph->search(base => $basedn,
                            filter => $filter,
                            attrs => ['proxyAddresses', 'mail'])
   or die "Can't search $@";

foreach my $entry ($search->entries) {
	parse_entry ($entry);
}

$ldaph->unbind();
write_file();
