#!/usr/bin/perl

use strict;

my($company_name) = shift(@ARGV);
my($base_dn) = shift(@ARGV);

unless ($company_name) {
	die("usage: passwd.imap2ldif.pl <company_name> [<base_dn>] < passwd.imap");
}

$base_dn = sprintf("DC=%s,DC=org", $company_name) unless ($base_dn);

printf("dn: DC=%s,DC=org
objectClass: top
objectclass: dcObject
objectClass: organization
o: %s
dc: %s

", $company_name, $company_name, $company_name);

my(%domains);

while (<>) {
	chomp($_);
	my($mailbox, $domain, $pass, $name) = (/^([^:\@]+)\@([^:]+):([^:]+):::([^:]*)/);
	my($mail) = $mailbox.'@'.$domain;
	$name = $mail unless ($name);
	if ($pass =~ /^\{MD5\}/) {
		$pass =~ s/^\{MD5\}/{CRYPT}/;
	} else {
		$pass = '{CRYPT}'.$pass;
	}
	unless ($domains{$domain}) {
		printf("dn: OU=%s,%s
objectClass: top
objectClass: organizationalUnit
ou: %s
description: organizational unit of domain %s

dn: OU=users,OU=%s,%s
objectClass: top
objectClass: organizationalUnit
ou: users
description: organizational unit users of domain %s

dn: OU=public_addrbook,OU=%s,%s
objectClass: top
objectClass: organizationalUnit
ou: public_addrbook
description: public address book of domain %s

dn: OU=personal_addrbook,OU=%s,%s
objectClass: top
objectClass: organizationalUnit
ou: personal_addrbook
description: personal address book of domain %s

", $domain, $base_dn, $domain, $domain,
$domain, $base_dn, $domain,
$domain, $base_dn, $domain,
$domain, $base_dn, $domain);
		$domains{$domain} = 1;
	}
	printf("dn: UID=%s,OU=users,OU=%s,%s
objectClass: top
objectClass: person
objectClass: organizationalPerson
objectClass: inetOrgPerson
userPassword: %s
uid: %s
cn: %s
sn: %s

", $mail, $domain, $base_dn, $pass, $mail, $name, $name);

	printf("dn: MAIL=%s,OU=public_addrbook,OU=%s,%s
objectClass: top
objectClass: person
objectClass: organizationalPerson
objectClass: inetOrgPerson
mail: %s
o: %s
cn: %s
sn: %s
displayName: %s

", $mail, $domain, $base_dn, $mail, $domain, $name, $name, $name);

	printf("dn: OU=%s,OU=personal_addrbook,OU=%s,%s
objectClass: top
objectClass: organizationalUnit
ou: %s
description: personal address book of %s

", $mail, $domain, $base_dn, $mail, $name);
}
