#!/usr/bin/perl
#
# Copyright (c) 2018, AT&T Intellectual Property. All rights reserved.
#
# SPDX-License-Identifier: LGPL-2.1-only
#
# The purpose of this script is to block tables from being deleted
# when they are still in use by PBR. An exit code of zero indicates
# the table may be deleted and non-zero indicates it should be
# retained.
#

use strict;
use warnings;

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

use Vyatta::VPlaned;

#
# Update controller and dataplane with the PBR tableid to kernel
# tableid mapping for newly created vrf.
# When the VRF is instantiated, there may already be some tableids
# defined so find them and send them to controller.
#
sub update_pbr_tablemap {
    my $vrf_name = shift;
    my $vrf_id   = shift;

    my $ctrl = new Vyatta::VPlaned;

    open my $fh, '<', "/run/route-domain.conf";
    while (my $line = <$fh>) {
	if ( $line =~ /^$vrf_name /) {
            my ($name, $ptid, $ktid) = split / /,$line;
            $ctrl->store("tablemap-$vrf_name-$ktid",
                         "tablemap $vrf_name $ptid $ktid $vrf_id",
                         "ALL", "SET");
        }
    }

    close $fh;
}

my $vrf_name = shift;
my $vrf_id   = shift;

update_pbr_tablemap($vrf_name, $vrf_id);
