#!/usr/bin/perl

use strict;
use warnings;

use English;
use Getopt::Long;
use NGCP::API::Client;
use Pod::Usage;
use Readonly;

Readonly my @required => qw();

my $opts = {
    verbose => 0,
};

GetOptions($opts,
    'help|h' => sub { usage() },
    'verbose',
) or usage();

sub check_params {
    my @missing;

    foreach my $param (@required) {
        push @missing, $param unless $opts->{$param};
    }
    usage(join(' ', @missing)) if scalar @missing;

    return;
}

sub usage {
    my $missing = shift;

    pod2usage(
        -exitval => $missing ? 1 : 0,
        -verbose => 1,
        -message => $missing ? "Missing parameters: $missing" : '',
    );

    return;
}

sub main {
    check_params();

    my $client = NGCP::API::Client->new(verbose => $opts->{verbose});

    my $uri = '/api/domains/';
    my $res = $client->request('GET', $uri);

    if (defined $res->as_hash->{total_count}) {
        print "API is up\n";
        return 0;
    } else {
        print "API is down\n";
        return 1;
    }
}

exit main();

__END__

=head1 NAME

ngcp-api-ping - check NGCP API status

=head1 SYNOPSIS

B<ngcp-api-ping> [I<options>]

=head1 DESCRIPTION

B<This program> checks whether NGCP API is running.

=head1 OPTIONS

=over 8

=item B<--help>

Print a brief help message.

=item B<--verbose>

Show additional debug information. Default false.

=back

=head1 EXIT STATUS

=over

=item B<0>

Command completed successfully.

=item B<1>

Command failed with errors.

=back

=head1 SEE ALSO

NGCP::API::Client

=head1 BUGS AND LIMITATIONS

Please report problems you notice to the Sipwise
Development Team <support@sipwise.com>.

=head1 AUTHOR

Victor Seva <vseva@sipwise.com>

=head1 LICENSE

Copyright (C) 2016 Sipwise GmbH, Austria

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

=cut