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

use strict;
use warnings;

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

use Getopt::Long;
use Vyatta::VPlaned;

use vyatta::proto::GArpConfig;

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

sub main {

    my ( $dev, $action, $garp );

    GetOptions(
        "dev=s"    => \$dev,
        "action=s" => \$action,
        "garp=s"   => \$garp,

    ) or usage();

    process_garp_cmd( $action, $garp, $dev ) if ($garp);

    exit 0;
}

sub usage {
    print <<EOF;
Usage: $0 --action=<action> --garp=<garp> --dev=<interface>
EOF
    exit 1;
}

sub setup_garp {
    my ( $action, $garp, $ifname ) = @_;
    my $cstore = new Vyatta::VPlaned;
    my ( $pkt, $dp_action ) = split( ',', $garp );

    my $value =
      $dp_action eq 'drop'
      ? GArpConfig::GarpPktAction::GARP_PKT_DROP()
      : GArpConfig::GarpPktAction::GARP_PKT_UPDATE();

    my $actionBool = $action eq 'SET' ? 1 : 0;

    my $arpOp =
      $pkt eq 'request'
      ? GArpConfig::ArpOp::ARPOP_REQUEST()
      : GArpConfig::ArpOp::ARPOP_REPLY();

    my $garpconfig = GArpConfig->new(
        {
            ifname => $ifname,
            action => $value,
            set    => $actionBool,
            op     => $arpOp,
        }
    );

    $cstore->store_pb( "garp $ifname $pkt", $garpconfig, "vyatta:garp",
        "$ifname");
}

sub process_garp_cmd {
    my ( $action, $garp, $dev ) = @_;
    my $value;

    if ( !defined($dev) ) {
        $dev = "all";
    }
    setup_garp( $action, $garp, $dev );
}
