#!/usr/bin/perl
#################################################
#                                               #
# fu 1.0                                        #
#                                               #
# Written by Maximilian E. <mle@multinion.de>,  #
# November 2004.                                #
#                                               #
#################################################

my $Formatting	= 1;
my $Start	= 0;
my $Stop	= 0;
my @Uid		= ();

# If you do not want colors,
# comment out the next 4 lines:
my $M1		= '[1m';
my ($MF1, $MF2)	= ('[0;36m', '[1;36m');
my ($MN1, $MN2)	= ('[0;33m', '[1;33m');
my $M0		= '[0m';

while( my $arg = shift @ARGV ) {
	if (($arg eq '-h') || ($arg eq '--help')) { print
		"${M0}usage: ${M1}fu${M0} [${M1}OPTIONS${M0}] [${M1}START${M0}]\n" .
		"Shows the first free user ID in the range ${M1}START${M0}+1 to ${M1}START${M0}+999.\n\n" .
		"  ${M1}-n${M0} / ${M1}--numeric${M0}  Unformatted output without any text.\n" .
		"  ${M1}-h${M0} / ${M1}--help${M0}     Displays this help.\n" .
		"  ${M1}-v${M0} / ${M1}--version${M0}  Displays program version.\n\n".
		"If no free UID in the given range could be found, ${M1}fu${M0}\n" .
		"returns error code ${M1}1${M0} (and UID ${M1}-1${M0} if ${M1}--numeric${M0} is set).\n" .
		"Default  value  for  ${M1}START${M0}  is  ${M1}0${M0}, so  ${M1}fu${M0}  without a\n" .
		"${M1}START${M0} value will give you the first free system UID.\n" .
		"${M1}fu${M0} is an abbrevation for ${M1}f${M0}ree ${M1}u${M0}id.\n\n";
		exit 0;
	} elsif (($arg eq '-v') || ($arg eq '--version')) { print
		"fu 1.0\n" .
		"Written by Maximilian E. <mle\@multinion.de>,\n" .
		"November 2004.\n\n";
		exit 0;
	} elsif (($arg eq '-n') || ($arg eq '--numeric')) {
		$Formatting = 0;
	} elsif ($arg > 0) {
		$Start = int $arg;
	}
}

open PWFH, '< /etc/passwd';
while( <PWFH> ) { $Uid[ (split /:/o)[2] ]++; }
close PWFH;

$Stop = $Start++ + 999;

foreach ($Start .. $Stop) {
	if (! $Uid[$_]) {
		print $Formatting
			? "${MF1}Free UID ${MF2}$_${M0}\n"
			: $_;
		exit 0;
	}
}

print $Formatting
	? "${MN1}Found no free UID in range ${MN2}$Start${MN1} - ${MN2}$Stop${M0}\n"
	: -1;
exit 1;
