#! /usr/bin/perl
# Copyright (c) 2020-2021, AT&T Intellectual Property. All rights reserved.
#
# SPDX-License-Identifier: LGPL-2.1-only
#

use strict;
use warnings;

use lib '/opt/vyatta/share/perl5/';

use Getopt::Long;
use Vyatta::Configd;
use Vyatta::Config;
use Readonly;
use File::Basename;

my $action;

Readonly my $SCRIPT_NAME => basename($0);

sub action_show_slowpath {

    my $usage = sub {
        printf( "Usage for %s --action=slowpath-info\n", $SCRIPT_NAME );
        printf( "    %s --action=slowpath-info --port=<port-name>\n",
            $SCRIPT_NAME );
        exit(1);
    };

    my $port;
    GetOptions( "port=s" => \$port, )
      or $usage->();
    $usage->() unless defined $port;

    my $if_dir = "/sys/class/net/$port";
    if ( !( -d $if_dir ) ) {
        printf "Interface $port does not exist on system\n";
        exit(1);
    }

    my $client = Vyatta::Configd::Client->new();
    my $t_info = $client->call_rpc_hash( "vyatta-interfaces-dataplane-rpc-v1",
        "slowpath-info", { 'name' => $port } );
    my $info_hash = %$t_info{'slowpath-info'};

    print "Dataplane interface: $info_hash->{name}\n";
    foreach my $key ( sort keys(%$info_hash) ) {
        my $val = $info_hash->{$key};
        next if $key eq "name";
        printf "   %-18s : ", $key;
        if ( ref($val) ) {
            print "\n";
            printf "      %-15s : %s\n", $_, $val->{$_}
              foreach ( sort keys(%$val) );
        } else {
            printf "%s\n", $val;
        }
    }

}

sub call_action_by_name {
    my ( $actions, $script_name, $opt_name, $usage ) = @_;

    my $usagefn = sub {
        printf( "Usage for %s %s:\n", $script_name, $usage );
        printf( "  %s %s --%s=[%s]\n",
            $script_name, $usage, $opt_name, join( "|", keys( %{$actions} ) ) );
        exit(1);
    };

    my ($name);
    GetOptions( "$opt_name=s" => \$name, )
      or $usagefn->();
    $usagefn->() unless defined $name;

    my $action = $actions->{$name};
    $usagefn->() unless defined $name;

    return $action->();
}

my %actions = ( "slowpath-info" => \&action_show_slowpath, );

call_action_by_name( \%actions, $SCRIPT_NAME, "action", "" );

exit 0;
