#!/usr/bin/perl
#
# Copyright (c) 2019, AT&T Intellectual Property. All rights reserved.
#
# SPDX-License-Identifier: GPL-2.0-only
#
# YANG RPC script used to extract & return the forwarding database
# (FDB) for a given switch or bridge interface.
#
# To test the script try something like this:
#
#  callrpc vyatta-interfaces-switch-v1 switch-fdb json '{"switch":"sw1"}' | json_pp
#
use lib "/opt/vyatta/share/perl5/";

use strict;
use warnings;
use JSON;

use Vyatta::FDB qw(fdb_collect);

my $debug   = 0;
my $logfile = "/var/tmp/getfdb.log";
my $fh;

open( $fh, '>', $logfile )
  or die "Could not open file '$logfile' $!"
  if ($debug);

my $input = join( '', <STDIN> );
my $rpc = decode_json $input;

print $fh "Input is: $input\n" if defined($fh);

my $bridge = $rpc->{'switch'};
$bridge = $rpc->{'bridge'} if not defined($bridge);
die "missing mandatory switch/bridge interface\n" if not defined($bridge);

my $fdb    = fdb_collect($bridge);
my %output = ();
my @ports  = ();
my $ifname = $rpc->{'port-name'};
my $mac    = $rpc->{'mac-address'};
foreach my $ifn ( sort( keys %{$fdb} ) ) {
    next if defined($ifname) and $ifname ne $ifn;

    my %portentry = ();
    my @fdblist   = ();
    my $index     = 0;
    foreach my $entry ( @{ $fdb->{$ifn} } ) {
        next if defined($mac) and $mac ne $entry->{'mac'};

        my %fdbentry = %$entry;
        $fdbentry{'index'} = ++$index;
        push @fdblist, \%fdbentry;
    }

    $portentry{'port-name'}           = $ifn;
    $portentry{'forwarding-database'} = \@fdblist;
    push @ports, \%portentry;
}

$output{'ports'} = \@ports;

my $json = encode_json( \%output );

print $fh "Output is: $json\n" if defined($fh);

print $json;
