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

# For interface config validation ONLY.
# Platform specific deviation to either warn or fail setting link speed.

use strict;
use warnings;

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

use Vyatta::Config;
use Getopt::Long;

# This is a "modulino" (http://www.drdobbs.com/scripts-as-modules/184416165)
exit __PACKAGE__->main()
  unless caller();

sub main {
    my ( $warn_speed, $ifp_filter, $rep_fail );

    GetOptions(
        "warn-speed=s" => \$warn_speed,
        "filter=s"     => \$ifp_filter,
        "report-fail"  => \$rep_fail,
    ) or usage();

    validate_link_speed( $warn_speed, $ifp_filter, $rep_fail )
      if ($warn_speed);

    exit 0;
}

sub usage {
    print <<EOF;
Usage: $0 --warn-speed=<speed> --filter=<regexp> [--report-fail]
EOF
    exit 1;
}

# Generate a warning message if the sspeed matches the wspeed and the
# interface matches with the filter regex.
# Exit 1 if there is a match and ret_fail is defined i.e. a validation
# failure is reported.
# Exit 0 otherwise (no validation failure).
sub validate_link_speed {
    my ( $wspeed, $filter, $ret_fail ) = @_;
    my $fail   = 0;
    my $config = Vyatta::Config->new();

    foreach my $ifname ( $config->listNodes('interfaces dataplane') ) {
        next unless ( defined($filter) && $ifname =~ /$filter/ );
        my $path;

        $path = sprintf "interfaces dataplane %s speed", $ifname;
        my $sspeed = $config->returnValue($path);
        $path = sprintf "interfaces dataplane %s disable", $ifname;
        my $disable = $config->exists($path);

        if ( $wspeed eq $sspeed && !defined($disable) ) {
            printf "Speed %s is not supported on port %s\n", $sspeed, $ifname;
            $fail = 1;
        }
    }
    exit 1 if ( defined($ret_fail) && $fail );
    exit 0;
}
