#!/usr/bin/perl
#
# $Id$

use strict;

use constant UIDSTART => 100;
use constant GIDSTART => 100;
use constant MAILPREFIX => "/var/lib/maildirs";

my %users;
my %groups;

# Read all users
open(PASSWD, "/etc/passwd");
while(<PASSWD>){
    chomp;
    m/^(.+):(.*):(.+):(.*):(.*):(.*):(.*)$/;
    next if ($3 < UIDSTART);
    $users{$1} = {};
    $users{$1}{'uidNumber'}        = $3;
    $users{$1}{'gidNumber'}        = $4;
    $users{$1}{'cn'}               = $5 || "N/A";
    $users{$1}{'homeDirectory'}    = $6 || "N/A";
    $users{$1}{'loginShell'}       = $7 || "/bin/false";
    $users{$1}{'mailMessageStore'} = MAILPREFIX."/$1";
 }
close(PASSWD);

# Read all groups
open(GROUP, "/etc/group");
while(<GROUP>){
    chomp;
    m/^(.+):(.*):(.+):(.*)/;
    next if ($3 < GIDSTART);
    $groups{$1} = {};
    $groups{$1}{'gidNumber'} = $3;
}
close(GROUP);

# Read all passwords
open(SHADOW, "/etc/shadow");
while(<SHADOW>){
    m/^(.+):(.+):(.*):(.*):(.*):(.*):(.*):(.*):(.*)$/;
    if ($users{$1}{'uidNumber'}){
	$users{$1}{'userPassword'} = "{crypt}$2";
    }
}
close(SHADOW);

# Generate ldif
foreach my $key (keys(%users)){
    if (! $users{$key}{'userPassword'}){
	$users{$key}{'userPassword'} = "{crypt}*";
    }
    print "dn: uid=$key,ou=people,dc=skole,dc=skolelinux,dc=no\n";
    print "objectclass: posixAccount\n";
    print "objectclass: imapUser\n";
    print "uid: ". $key ."\n";
    print "cn: ". $users{$key}{'cn'} ."\n";
    print "uidNumber: ". $users{$key}{'uidNumber'} ."\n";
    print "gidNumber: ". $users{$key}{'gidNumber'} ."\n";
    print "homeDirectory: ". $users{$key}{'homeDirectory'} ."\n";
    print "mailMessageStore: ". $users{$key}{'mailMessageStore'} ."\n";
    print "userPassword: ". $users{$key}{'userPassword'} ."\n";
    print "loginShell: ". $users{$key}{'loginShell'} ."\n";
    print "\n";
}
foreach my $key (keys(%groups)){
    print "dn: cn=$key,ou=group,dc=skole,dc=skolelinux,dc=no\n";
    print "objectclass: posixGroup\n";
    print "cn: ". $key ."\n";
    print "gidNumber: ". $groups{$key}{'gidNumber'} ."\n";
    print "\n";
}
