#!/usr/bin/perl -w
# ------------------------------------------------------------
# script:  ldapdumpusers.pl
# Author:  Brad Marshall (bmarshal@pisoftware.com)
# License: GPL
# Date:    20000203
#
# Purpose: Dumps the users into an /etc/passwd type file
#
# Copyright (c) 2000 Plugged In Software Pty Ltd.  All rights reserved.

use strict;
use Net::LDAP;

my($ldap) = Net::LDAP->new('ldap.staff.plugged.com.au') or die "Can't bind to ldap: $!\n";

$ldap->bind;

my($mesg) = $ldap->search( base => "dc=pisoftware,dc=com",
					   filter => '(objectclass=account)');

$mesg->code && die $mesg->error;

my($entry,$attr);

my(%results);
foreach $entry ($mesg->entries) {
	#print "DN = ",$entry->dn,"\n";
	#foreach $attr ($entry->attributes) {
	#	print $attr,": ", join(" ", $entry->get($attr)), "\n";
	#}
#	print $entry->get('cn'), " ", $entry->get('gidnumber'), "\n";
	#printf "%3d\t%s\n",$entry->get('gidnumber'), $entry->get('cn');

# postgres:!!:113:113:PostgreSQL Server:/var/lib/pgsql:/bin/sh
# uid:userpassword:uidnumber:gidnumber:gecos:homedirectory:loginshell

	my($tmpcn) = $entry->get('uid');
	my($tmpnum) = $entry->get('uidnumber');
	my($tmpgid) = $entry->get('gidnumber');
	my($tmppassword) = $entry->get('userpassword');
	if ($tmppassword) {
		$tmppassword =~ s/^{crypt}//;
	}
	#my($tmpgecos) = $entry->get('gecos') || [ "Plugged In User" ];
	my($tmpgecos) = $entry->get('cn');
	$tmpgecos ||= "";
	my($tmphome) = $entry->get('homedirectory');
	my($tmpshell) = $entry->get('loginshell');
	$tmpshell ||= "";

	#if ($tmpcn eq "root") {
	#	print "Root passwd = $tmppassword\n";
	#}
	if (! $tmppassword) {
		$tmppassword = "x";
	}
	my($tmpstr) = "$tmppassword:$tmpnum:$tmpgid:$tmpgecos:$tmphome:$tmpshell";
	#print "$tmpcn\n";
	$results{$tmpcn} = $tmpstr;
}

sub bygroup {
	(split /:/,$results{$a})[1] <=> (split /:/,$results{$b})[1]
}

my($foo);
foreach $foo (sort bygroup keys %results) {
	#printf "%3d\t%s\n",$results{$foo}, $foo;
	print "$foo:$results{$foo}\n";
}

$ldap->unbind;


