#!/usr/bin/perl

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

=head1 NAME

    la-sql-switch-cname - Exchange (c)name between two host

=head1 SYNOPSIS

    la-exchange-ip cname [cname] [-a name] desthost

Example : la-rename-host foo bar

=cut

GetOptions(
    'c|config=s'        => \my $config,
    'b|base=s'          => \my $base,
    'cname|cn=s'        => \my @cnames,
    'a|arecord=s'       => \my @arecords,
    '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);

if (!@ARGV) {
    pod2usage(1);
}
    
my ($to, $from) = ($ARGV[-1], $ARGV[-2]);

my $oto = $labase->get_object('nethost', $to) or die "Cannot find $to\n";

foreach my $cname (@cnames) {
    my @listhost = $labase->search_objects('nethost', "cname=$cname");
    my ($nhost, @others) = $from
        ? grep { $_ eq $from } @listhost
        : @listhost;
    if (@others) {
        die "Multiple hosts found for $cname: " . join(', ', $nhost, @others) . "\n";
    } elsif (!$nhost) {
        die "No cname $cname found\n";
    } elsif ($nhost eq $to) {
        die "Source and destination are the same host for cname $cname\n";
    }
    my $onhost = $labase->get_object('nethost', $nhost);
    warn "CNAME $cname: $nhost => $to\n";

    {
        my @name = grep { $_ && $_ ne $cname } $onhost->get_attributes('cname');
        $onhost->set_c_fields(cname => @name ? [ @name ] : undef) or die "Cannot set $cname to $nhost\n";
    }
    
    {
        my @name = $cname, $oto->get_attributes('cname');
        $oto->set_c_fields(cname => [ grep { $_ } @name ]) or die "Cannot add $cname to $to\n";
    }
}
foreach my $aname (@arecords) {
    my @listhost = $labase->search_objects('nethost', "otherName=$aname");
    my ($nhost, @others) = $from
        ? grep { $_ eq $from } @listhost
        : @listhost;
    if (@others) {
        die "Multiple hosts found for $aname: " . join(', ', $nhost, @others) . "\n";
    } elsif (!$nhost) {
        die "No otherName $aname found\n";
    } elsif ($nhost eq $to) {
        die "Source and destination are the same host for a $aname\n";
    }
    my $onhost = $labase->get_object('nethost', $nhost);
    warn "CNAME $aname: $nhost => $to";

    {
        my @name = grep { $_ && $_ ne $aname } $onhost->get_attributes('otherName');
        $onhost->set_c_fields(otherName => @name ? [ @name ] : undef) or die "Cannot set $aname to $nhost\n";
    }
    
    {
        my @name = $aname, $oto->get_attributes('otherName');
        $oto->set_c_fields(otherName => [ grep { $_ } @name ]) or die "Cannot add $aname to $to\n";
    }
}

$labase->commit;
