#!/usr/bin/perl
#
# Copyright (c) 2017 by Brocade Communications Systems, Inc.
# All rights reserved.
#
# SPDX-License-Identifier: GPL-2.0-only
#

use strict;
use warnings;
use lib '/opt/vyatta/share/perl5/';
use Vyatta::Interface;
use Vyatta::Config;

my $intf_path = "/etc/network/interfaces.d/";

sub write_entry {
    my ( $name, $addr, $is_ipv6 ) = @_;

    my $af = "inet6";
    $af = "inet" unless $is_ipv6;

    my $filename = $intf_path . $name . "_" . $af;

    open my $fh, '>', $filename or die "couldn't write sysintf entry";
    print $fh "# Autogenerated entry for system interface $name\n";
    print $fh "auto $name\n";
    print $fh "iface $name $af static\n";
    print $fh "address $addr\n";
    close $fh;
}

# For system interfaces with static addresses, write entries
# to /etc/network/interfaces so that they are automatically
# configured on reboot and ready for any services (such as the
# dataplane on a VDR vplane node) that require a network address
# before configd has applied config.
#
# The addressing has already been validated and applied. We are
# simply ensuring consistency in /etc/network/interfaces so no need
# to revalidate here.
#
sub write_sysintf_persistence {
    while ( my $name = shift ) {
        my $intf = new Vyatta::Interface($name);
        my $cfg  = new Vyatta::Config( $intf->path() );

        my $static_v4 = 0;
        my $static_v6 = 0;

        foreach my $addr ( $cfg->returnValues('address') ) {
            next if ( $addr =~ /dhcp/ );

            if ( $addr =~ /:/ ) {
                $static_v6 = 1;
                write_entry( $name, $addr, 1 );
            } else {
                $static_v4 = 1;
                write_entry( $name, $addr, 0 );
            }
        }

        # Remove any unused entries
        my $filename = $intf_path . $name . "_" . "inet";
        if ( -e $filename && !$static_v4 ) {
            unlink $filename;
        }

        $filename = $intf_path . $name . "_" . "inet6";
        if ( -e $filename && !$static_v6 ) {
            unlink $filename;
        }
    }
}

`vyatta-intf-end @ARGV`;
write_sysintf_persistence(@ARGV);
