#!/usr/local/bin/perl -w
##############################################################################
# $Id: ldapposixadd,v 1.2 2002/02/22 00:43:11 jheiss Exp $
##############################################################################
# Bring up a template for a LDAP user or group entry in $EDITOR and allow
# the user to edit it.
# When the user exits the editor, save the new entry to LDAP.
#
# TODO:
# - Password
# - Allow user to specify options to ldapadd, like -x
# - Add the option of using Net::LDAP instead of the command-line tools
##############################################################################
# $Log: ldapposixadd,v $
# Revision 1.2  2002/02/22 00:43:11  jheiss
# Use /usr/local/bin/perl -w
#
# Revision 1.1  2002/02/09 03:25:34  jheiss
# Initial revision
#
##############################################################################

# Includes and such
use POSIX;

# Constants
my $USER_TEMPLATE='template.user';
my $GROUP_TEMPLATE='template.group';

# Globals

sub usage
{
	die "Usage: $0 {passwd|group}\n";
}

if (scalar @ARGV == 0)
{
	usage();
}

if ($ARGV[0] eq 'passwd')
{
	open(TEMPLATE, "< $USER_TEMPLATE") ||
		die "Failed to open template file $USER_TEMPLATE\n";
}
elsif ($ARGV[0] eq 'group')
{
	open(TEMPLATE, "< $GROUP_TEMPLATE") ||
		die "Failed to open template file $GROUP_TEMPLATE\n";
}
else
{
	usage();
}

# Amazingly, Perl doesn't seem to have a clean mkstemp implementation...
# This came from a Tom Christiansen email I found via a Google search for
# perl and mkstemp.
my $tmpfile;
do
{ 
	$tmpfile = tmpnam();
} until sysopen(TF, $tmpfile, O_RDWR|O_CREAT|O_EXCL, 0666);

$SIG{INT} = cleanup;

# Copy the template into the temp file
print TF <TEMPLATE>;
close(TEMPLATE);

close(TF);

if ($ENV{'EDITOR'})
{
	system("$ENV{'EDITOR'} $tmpfile");
}
else
{
	system("vi $tmpfile");
}

open(TF, "< $tmpfile") || cleanup("Failed to re-read temp file\n");

# ldapadd will exit without any command line options.  We don't really
# need any, specifying LDAPv3 seems fairly innocuous.
$SIG{PIPE} = 'IGNORE';  # Recommended by the perlipc man page
open(LA, "| ldapadd -P 3") || cleanup("Failed to fork ldapadd\n");
print LA <TF>;
close(LA) || cleanup("ldapadd exitted with error\n");

cleanup();

sub cleanup
{
	my $message = shift;

	print STDERR $message if ($message);

	print STDERR "Cleaning up\n";
	unlink($tmpfile);

	exit(1) if ($message);
	exit(0);
}

