#!/usr/local/bin/perl
#
# $Id: usergetid,v 1.2 2004/05/26 19:21:10 forun Exp $
#
# Contributed by Manon Goo <manon@manon.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

use Getopt::Long;
use Term::ReadLine;

require 'usertools.ph';

&GetOptions("count:i");

my @uids = ();
$lastuid = 1001;

# Connect to LDAP
$ldap = ldap_connect() || exit(1);

if ( $opt_count ) {
	for ($i=0;$i < $opt_count;$i++){
		print get_uid(), "\n";
	}
} else {
	print get_uid(), "\n";
}
sub get_uid {
  if (!@uids) {

    print STDERR "Getting list of UIDs - this could take several seconds\n";
    my $mesg = $ldap->search(base => $config{userbase},
                             filter => "(objectclass=posixAccount)",
                             attrs => ['uidNumber']);
    print $mesg->error if $mesg->code;
    @entry = $mesg->entries;
    for (@entry) {
      my $uid = $_->get_value("uidNumber");
      if ($uid) {
        $uids[$uid] = 1;
      }
    }
  }

  while (1) {
    if ($uids[$lastuid]) {
      $lastuid++;
    } else {
      if (($ldap->search(base=>$config{userbase},
                         filter => "(uidNumber=$lastuid)" ))->entry()) {
        $uids[$lastuid++] = 1;
      } else {
        $uids[$lastuid] = 1;
        $u{uidnumber} = $lastuid++;
        return $u{uidnumber};
      }
    }
  }
}

__END__
=head1 NAME

usergetid - Gets the lowest available user ID (uidNumber).

=head1 SYNOPSIS
     
B<usercreate> [--count] I<number>

=head1 DESCRIPTION

B<usergetid> Finds the next available user IDs (uidNumber).

=head1 OPTIONS

B<--count> I<number>

Number of UIDs to return.

=cut 

