#!/usr/bin/env perl

use 5.010;
use warnings;
use strict;

use Test::Consul;
use Getopt::Long::Descriptive;
use Defined::KV;

my ($opt, $usage) = describe_options(
  '%c %o',
  [ 'port=i',       'port for HTTP API port', { default => 8500 } ],
  [ 'node=s',       'node name' ],
  [ 'datacenter=s', 'datacenter name' ],
  [ 'cluster=i',    'start a cluster of N nodes', { default => 1 } ],
  [ 'help|h',       'print usage message and exit', { shortcircuit => 1 } ],
);

print $usage->text and exit if $opt->help;

my $port = $opt->port;
my $node_name = $opt->node;
my $datacenter = $opt->datacenter;

my @nodes;
for (1..$opt->cluster) {
  my $node = Test::Consul->start(
    defined_kv(port       => $port),
    defined_kv(node_name  => $node_name),
    defined_kv(datacenter => $datacenter),
  );

  if (@nodes) {
    $nodes[-1]->join($node);
  }
  push @nodes, $node;

  undef $port;
  undef $node_name;
  $datacenter = $nodes[-1]->datacenter;
}

while (1) { sleep 86400 }

=pod

=encoding UTF-8

=head1 NAME

test-consul - Run a Consul server for testing

=head1 SYNOPSIS

    # run a simple server (not unlike 'consul agent -dev')
    $ test-consul

=head1 DESCRIPTION

C<consul-test> runs a test consul instance on your local computer, that you can then manipulate with the normal C<consul> program. Useful for trying things out!

=head1 OPTIONS

=head2 port

The TCP port for HTTP API endpoint. By default this is C<8500>, which is what the standard C<consul> client program expects.

=head2 name

Set the node name. If not supplied, a random one will be generated.

=head2 datacenter

Set the datacenter name. If not supplied, a random one will be generated.

=head1 SEE ALSO

L<Test::Consul>

=cut