#!/usr/bin/perl

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

=head1 NAME

    la-sql-exchange-ip - Exchange name between two host

=head1 SYNOPSIS

    la-exchange-ip from to

Example : la-sql-exchange-hostname foo bar

=cut

GetOptions(
    'c|config=s'        => \my $config,
    'b|base=s'          => \my $base,
    'help'              => sub { pod2usage(0) },
) 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.

=back

=cut

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

$labase->unexported(1);

my ($from, $to) = @ARGV or pod2usage();

$labase->get_object('nethost', $from) or die "Cannot find host $from";
$labase->get_object('nethost', $to) or die "Cannot find host $to";

my $tempname;
while (1) {
    $tempname = $from . '-' . join('', map { ('a' .. 'z')[rand(26)] } (0 .. 7));
    $labase->get_object('nethost', $tempname) or last;
}

$labase->rename_object('nethost', $from, $tempname) or die "Cannot rename $from to a temporary name\n";
$labase->rename_object('nethost', $to, $from) or die "Cannot rename $to to $from\n";
$labase->rename_object('nethost', $tempname, $to) or die "Cannot rename $from to a its final name $to\n";

$labase->commit;
print "Exchange between $from and $to done\n";

