#!/bin/bash
#
# ::copy::
# ::maintainer::
#
CMD=`basename $0`

set -u

usage()
{
	echo -e "\nusage: $CMD uid\n" >&2
	exit 1
}

[ $# != 1 ] && usage

start_uid=$1
uid=$1
tryes=0
maxtryes=5000

# first, search in ldap
#
while :
do
	res=`ldapsearch -x uidNumber=$uid` || exit $?
	echo "$res" | grep -q numEntries || {

		# second, checks passwd
		#
		for id in `getent passwd | awk -F":" '{ print $3 }'`
		do
			[ $id == $uid ] && break
		done
		[ $id != $uid ] && {
			echo $uid
			break
		}
	}
	uid=`expr $uid + 1`
	tries=`expr $tryes + 1`
	[ $tryes -gt $maxtryes ] && {
		echo "error: too many tryes (>$maxtryes)" >&2
		echo "  something was wrong with starting uid=$start_uid" >&2
		exit 1
	}
done

exit 0
