#!/usr/bin/perl

use v5.36;

use JSON::XS;

my @out = qx(/usr/sbin/ngcp-kamctl proxy dispatcher dump);
die "cannot talk to kamailio proxy: $?\n" if $?;

my %peers = ();

use constant PEER_PROBE_ID => 100;

my $probe_id;

my $peers = decode_json("@out");

foreach my $record (@{$peers->{RECORDS}}) {
    my $probe = $record->{SET};

    my $probe_id = $probe->{ID};

    next unless defined $probe_id and $probe_id == PEER_PROBE_ID;

    foreach my $target (@{$probe->{TARGETS}}) {
        my $uri = $target->{DEST}->{URI};
        my $flags = $target->{DEST}->{FLAGS};
        my $attrs = $target->{DEST}->{ATTRS}->{BODY};

        my $peerid = $attrs =~ s/^.*peerid=(\d+).*$/$1/r;
        my $peername = $attrs =~ s/^.*peername="([^"]+)".*$/$1/r;
        my $peergid = $attrs =~ s/^.*peergid=(\d+).*$/$1/r;

        my $check = 'unknown';
        if ($flags =~ /P/i) {
            $check = 'yes';
        } elsif ($flags =~ /X/i) {
            $check = 'pending';
        }

        my $status = 'unknown';
        if ($flags =~ /A/i) {
            $status = 'up';
        } elsif ($flags =~ /I/i) {
            $status = 'down';
        }

        $peers{$peername} = {
            id => $peerid,
            name => $peername,
            groupid => $peergid,
            uri => $uri,
            check => $check,
            status => $status,
        };
    }
}

# Print the list of peers and their current status.
my @peers = sort { $peers{$a}->{status} cmp $peers{$b}->{status} } keys %peers;
foreach my $peername (@peers) {
    my $peer = $peers{$peername};
    my $status = uc $peer->{status};

    say "$status\tid=$peer->{id}\tname=$peer->{name} uri=$peer->{uri}";
}
