#!/usr/bin/perl

use strict;
use warnings;
use LATMOS::Accounts::BuildNet;
use Getopt::Long;
use Pod::Usage;

=head1 NAME

    la-freeip - Search unused ip in database

=head1 SYNOPSIS

    la-buildnet [-f|-r] zone [...]

=cut

GetOptions(
    'c|config=s'        => \my $config,
    'b|base=s'          => \my $base,
    'help'              => sub { pod2usage(0) },
    'n'                 => \my $network,
    'f|first'           => \my $first,
    'r|random'          => \my $random,
) or pod2usage();

=head1 OPTIONS

=over 4

=item -c|--config configdir

Use this configuration directory instead of the default one.

=item -b|--base basename

Query this specific base instead of the default one.

=item -f|--first

Return the first free ip

=item -r|--random

Return a random free ip in the unallocated pool

=back

=cut

my $LA = LATMOS::Accounts::BuildNet->new($config, noacl => 1);
my $labase = $base ? $LA->base($base) : $LA->default_base;
$labase && $labase->load or die "Cannot load base";

my @ips;
foreach (@ARGV) {
    my $ozone = $labase->get_object('netzone', $_) or die "Can't find zone $_";
    push(@ips, grep { $_ } $ozone->get_attributes('freeIP'));
}
if (@ips) {
    if ($first) {
        print "$ips[0]\n";
    } elsif ($random) {
        print $ips[rand($#ips)] . "\n";

    } else {
        print join('', map { "$_\n" } @ips);
    }
} else {
    warn "No free ip found\n";
}
