#!/usr/bin/env perl
# This script generates an LDIF for bulk adding users from /etc/passwd
#
# Can use `ypcat -k passwd | ./ldifpasswd.pl passwd.ldif | grep '^\.' -A 1 | grep -v '^\.\|^-'`
#    to get a listing of all the users to double check the givenName and sn of
#
# Then use `ldapmodify -v -h $host -p $port -D cn=Directory\ Manager -w $passwd -f passwd.ldif -a`
#    to add the users in

use strict;
use warnings;
use diagnostics;
use vars qw($fh);


# Get filehandle for LDIF output
unless ($ARGV[0]) {
	print STDERR "$0: Usage: `$0 outputfile`\n";
	exit 1;
}
open($fh, ">", $ARGV[0]) or die "Couldn't open '$ARGV[0]' for output";


# Read through all of stdin
while (my $line = <STDIN>) {
	chomp $line;
	my ($uname, $passwd, $uid, $gid, $gecos, $homedir, $shell) = split /:/, $line;
	
	# Clean up "uname passwdline" syntax
	$uname =~ s/(\S+)\s+\1/$1/;
	# Clean up gecos since they're grungy
	$gecos =~ s/^\s*(.*?)\s*$/$1/;
	$gecos =~ s/\s+/ /g;
	# Try to get name parts out of gecos and verify that we didn't overlook something funny
	my ($gn, $sn) = $gecos =~ m/^(\S+).*?(\S+)(?:\s+\(.*\))?$/;
	($gn, $sn) = ('', '') if ($gecos eq '');
	{
		my ($local_gn, $local_sn) = ($gn, $sn);
		my $magic = '\\' . join '|\\', qw! ( ) | \ . + * ? ^ $ [ ] { } !;
		$local_gn =~ s/($magic)/\\$1/g;
		$local_sn =~ s/($magic)/\\$1/g;
		if ($gecos !~ m/^$local_gn (?:\S+ )?$local_sn$/) {
			print "\n...Double check the name fields for user $uname\n";
		}
	}
	
	# List the fields found for each user
	printf "%-8s %5d,%4d  %-13s  %-18s    %-12s %-12s <- %s\n",
		$uname, $uid, $gid, $homedir, $shell, $gn, $sn, $gecos;
	
	# It'd be nice to interactively reset the givenName and sn here if broken,
	# but we're already reading from stdin...
	
	# Output LDIF
	print $fh join "\n",
		"dn: uid=$uname,ou=People, dc=catnip",
		"objectClass: top",
		"objectClass: person",
		"objectClass: organizationalPerson",
		"objectClass: inetorgperson",
		"cn: $gecos",
		"givenName: $gn",
		"sn: $sn",
		"uid: $uname",
		"userPassword: {CRYPT}$passwd==",
		#"passwordExpirationTime: $xxx",
		#"telephoneNumber: (555) 555-5555",
		#"mail: $uname@pdx.edu",
		'', '';
}

exit 0;
__END__
