#!/usr/bin/perl
##
# Check the responsiveness of a SIP server.
#
# Copyright © 2005-2006 O'Shaughnessy Evans <shaug+nagios@aloha.net>
# Copyright © 2011, 2015--2017 Sipwise GmbH, Austria
#
# Requires sipsak; see sipsak.org for more info.
##

use v5.36;

use Getopt::Long qw(:config no_ignore_case);
use NGCP::Gather::SIPOption;

my %ERRORS = (
    OK => 0,
    WARNING => 1,
    CRITICAL => 2,
    UNKNOWN => 3,
    DEPENDENT => 4,
);

my $ME = 'ngcp-check-sip-option';
my $VERSION = '0.1.5';

my %Flags;
my $URI;
my $Verbose = 0;
my $Proxy = '';
# Use a local port in 6000 <= port < 10000.
my $Local_Port = int(rand(4000) + 6000);
my $Perf = 0;
my $Warn_Threshold = 1;
my $Crit_Threshold = 5;

my $Usage = "$ME -U <sip-uri> [-P <proxy>] [-v] [-w <warn>] [-c <crit>] [-f]\n";
my $Help = <<EOF;
Usage:
  $ME [<option>...] -U <sip-uri>

Options:
  -U, --uri=<sip-uri> Full "sip:user\@host[:port]" URI.
  -P, --proxy=<name>  Outbound proxy hostname;
                        use if different than SIP URI host.
  -w, --warn=<secs>   Warning threshold (in seconds).
  -c, --crit=<secs>   Critical threshold (in seconds).
  -f, --perf          Include perfdata in result.
  -v, --verbose       Show progress details (repeated gives more information).
      --help          Show this usage text.
      --version       Show the version ($VERSION).
EOF

# Handle the command-line
GetOptions(
    'verbose|v+'   => \$Verbose,
    'version|V'    => \$Flags{version},
    'help|h'       => \$Flags{help},
    'proxy|P=s'    => \$Proxy,
    'uri|U=s'      => \$URI,
    'warn|w=s'     => \$Warn_Threshold,
    'crit|c=s'     => \$Crit_Threshold,
    'perf|f'       => \$Perf,
) or die($Usage);

if ($Flags{version}) {
    print "$ME $VERSION";
    exit 0;
} elsif ($Flags{help}) {
    print $Help;
    exit 0;
}

if (!$URI) {
    print "ERROR:  Sorry, but a full URI must be given.\n\n" . $Usage;
    exit $ERRORS{UNKNOWN};
}

my $sip = check_sip_option(
    verbose => $Verbose,
    uri => $URI,
    proxy => $Proxy,
    local_port => $Local_Port,
    warn_threshold => $Warn_Threshold,
    crit_threshold => $Crit_Threshold,
);

my $answer = $sip->{answer};
if (exists $sip->{duration}) {
    $answer .= "Duration: $sip->{duration}";
    if (defined $Perf && $Perf > 0) {
        $answer .= " | duration=$sip->{duration}";
    }
}

my $errname = uc $sip->{state};
my $rc = $ERRORS{$errname};
print "SIP $errname: $answer\n";
exit $rc;
