#!/usr/bin/perl -w
# this generates a Python-format mailmap for cvs2git
# Author: Robin H Johnson <robbat2@gentoo.org>
# License: BSD-2
#
# Will NOT work outside of Gentoo infrastructure hosts
use strict;
use warnings;
use Encode;
use Net::LDAP;
use Net::LDAP::Util qw(ldap_error_text);
use Unicode::Normalize;
use POSIX qw(strftime);
use utf8;
no encoding;

my $server = 'ldap://ldap1.gentoo.org';
my $basedn = 'dc=gentoo, dc=org';
my %devs = (
#	'robbat2' => ['Robin', 'robbat2@gentoo.org'],
);
use Data::Dumper;

my $ldap = Net::LDAP->new($server, version => 3, onerror => "die") || die "Connection Failed";
my $msg  = $ldap->start_tls( verify => 'required',
                          clientcert => '/etc/openldap/ssl/star.gentoo.org.crt',
                          clientkey  => '/etc/openldap/ssl/star.gentoo.org.key',
                          cafile     => '/etc/openldap/ssl/ca.pem' );
if ($msg->is_error) {
	die ldap_error_text($msg->code);
}

$msg = $ldap->bind;

if ($msg->is_error) {
	die ldap_error_text($msg->code);
}

my @args = ( base => $basedn, timelimit => 600 );
push @args, (filter => '(&(uidNumber=*)(!(gentooAccess=infra-system.group)))');
$msg = $ldap->search( @args );
$msg->code && die "error: ", $msg->error;
while (my $e = $msg->shift_entry()) {
	last unless defined($e);
	$_ = $e;
	my $user = lc $_->get_value('uid');
	my $email = sprintf('%s@gentoo.org', $user);
	my $fullname = $_->get_value('cn');
	chomp $fullname;
	chomp $user;
	my @aliases = sort $_->get_value('gentooAlias');
	my $uid = $_->get_value('uidNumber');
	# This generate extra alises like 'uidNNN' to work around a CVS issue.
	push @aliases, sprintf('uid%d', $uid)
		if defined($uid) && $uid ne 'undefined' && 0+$uid > 100;
	push @aliases, $user;
    my @keys = $_->get_value('gpgkey');
    if(!@keys || (length(@keys) == 0) || (length(@keys) == 1 && $keys[0] eq 'undefined')) {
        @keys = ();
    }
    foreach my $alias (sort @aliases) {
		chomp $alias;
        $devs{lc $alias} = [$fullname, $email, \@keys];
    }
}
#print Dumper(%devs);
#exit;

my $t = time;
printf "# Python mailmap generated from LDAP @ %s\n",strftime("%c",gmtime($t));
printf "# encoding: utf-8\n"; # Don't remove this, Python will default to ascii
printf "mailmap_ts=%d\n", $t;
printf "mailmap={\n";
map { 
    my $nick = $_;
    my $name = $devs{$_}[0];
    my $email = $devs{$_}[1];
    my $keys = $devs{$_}[2];
    my @keys = @$keys;
    my $ks = join(', ', map { chomp; sprintf "u'%s'", $_; } @keys);
    printf "\t".'u"%s": (u"%s", u"%s", (%s)),'."\n", $_, $devs{$_}[0], $devs{$_}[1], $ks;
} sort keys %devs;
printf "}\n";
