#  You may distribute under the terms of either the GNU General Public License
#  or the Artistic License (the same terms as Perl itself)
#
#  (C) Paul Evans, 2015 -- leonerd@leonerd.org.uk

package App::MatrixTool::Command::resolve;

use strict;
use warnings;
use base qw( App::MatrixTool );

our $VERSION = '0.01';

use Future::Utils qw( try_repeat );

use constant DESCRIPTION => "Look up hostname or IP addresses of a server";
use constant OPTIONS => (
   'a|address' => 'address',
);

sub run
{
   my $self = shift;
   my ( $opts, $server_name ) = @_;

   $self->http_client->resolve_matrix( $server_name )->then( sub {
      my @res = @_;
      # SRV records yield a 'weight' field, A/AAAA-based backup does not
      defined $res[0]->{weight}
         ? $self->output_info( "Resolved $server_name by SRV" )
         : $self->output_info( "Using legacy IP address fallback" );

      try_repeat {
         my $res = shift;

         $self->output( "target=$res->{target} port=$res->{port}" );

         $opts->{address} or
            return Future->done;

         $self->http_client->resolve_addr( $res->{target} )
            ->then( sub {
               my @addrs = @_;
               foreach my $addr ( @addrs ) {
                  $self->output( "  " . $self->format_hostport( $addr, $res->{port} ) );
               }
               Future->done;
            })
            ->else( sub {
               $self->output( "  address unknown [$_[0]]" );
               Future->done;
            });
      } foreach => \@res;
   });
}

0x55AA;
