#!/usr/bin/perl

use strict;
use warnings;

use Time::HiRes qw(usleep);

use PVE::Cluster;
use PVE::INotify;
use PVE::IPRoute2;
use PVE::Network::SDN;
use PVE::Network::SDN::Zones;
use PVE::Network::SDN::Vnets;
use PVE::Network::SDN::Subnets;
use PVE::Network::SDN::Controllers;
use PVE::Network::SDN::Fabrics;
use PVE::Tools;

for (my $i = 0; !PVE::Cluster::check_cfs_quorum(1); $i++) {
    print "waiting for pmxcfs mount to appear and get quorate...\n"
        if $i % 50 == 0;

    usleep(100 * 1000);
}

my $proxmox_firewall = '/usr/libexec/proxmox/proxmox-firewall';

# The conntrack zones are set for the interfaces that the kernel reports as enslaved to a zone VRF,
# so this needs to run after ifreload. The running config may have changed while the node was
# offline, so apply them even without pending changes.
sub apply_vrf_ct_zones {
    if (!-x $proxmox_firewall) {
        my $nodename = PVE::INotify::nodename();
        my $zones = PVE::Network::SDN::running_config()->{zones}->{ids} // {};
        warn "proxmox-firewall is not installed, connections are not isolated between zone VRFs\n"
            if grep { defined($_->{'ct-zone'}) && (!$_->{nodes} || $_->{nodes}->{$nodename}) }
            values $zones->%*;
        return;
    }

    eval { PVE::Tools::run_command([$proxmox_firewall, 'sdn-ct-zones']) };
    warn "failed to apply the conntrack zones of zone VRFs - $@" if $@;
}

sub has_pending_changes {
    my ($pending_config) = @_;

    for my $entity (values $pending_config->{ids}->%*) {
        return 1 if $entity->{state};
    }

    return 0;
}

sub fabrics_changed {
    my $current_config = PVE::Network::SDN::Fabrics::config();
    my $running_config = PVE::Network::SDN::Fabrics::config(1);

    my ($running_fabrics, $running_nodes) = $running_config->list_all();
    my ($current_fabrics, $current_nodes) = $current_config->list_all();

    my $pending_fabrics = PVE::Network::SDN::pending_config(
        { fabrics => { ids => $running_fabrics } },
        { ids => $current_fabrics },
        'fabrics',
    );

    my $pending_nodes = PVE::Network::SDN::pending_config(
        { nodes => { ids => $running_nodes } },
        { ids => $current_nodes },
        'nodes',
    );

    return has_pending_changes($pending_fabrics) || has_pending_changes($pending_nodes);
}

sub zone_uses_non_vlan_aware_bridge {
    my ($zone, $ip_links) = @_;

    return 0 if ($zone->{type} ne 'vlan' && $zone->{type} ne 'qinq');

    my $ip_link = $ip_links->{ $zone->{bridge} };
    return 0 if !defined($ip_link);

    return !PVE::IPRoute2::bridge_is_vlan_aware($ip_link);
}

sub sdn_changed {
    my $running_config = PVE::Network::SDN::running_config();

    my $configs = {
        zones => PVE::Network::SDN::Zones::config(),
        vnets => PVE::Network::SDN::Vnets::config(),
        subnets => PVE::Network::SDN::Subnets::config(),
        controllers => PVE::Network::SDN::Controllers::config(),
    };

    for my $type (keys $configs->%*) {
        my $pending_config = PVE::Network::SDN::pending_config(
            $running_config, $configs->{$type}, $type,
        );

        return 1 if has_pending_changes($pending_config);
    }

    my $ip_links = PVE::IPRoute2::ip_link_details();

    for my $zone (values $configs->{zones}->{ids}->%*) {
        return 1 if zone_uses_non_vlan_aware_bridge($zone, $ip_links);
    }

    for my $running_zone (values $running_config->{zones}->{ids}->%*) {
        return 1 if zone_uses_non_vlan_aware_bridge($running_zone, $ip_links);
    }

    return fabrics_changed();
}

if (!sdn_changed()) {
    print "No changes to SDN configuration detected, skipping reload\n";
    apply_vrf_ct_zones();
    exit 0;
}

my $previous_config_has_frr = PVE::Network::SDN::running_config_has_frr();
# serialize with applying the SDN config via the API on another node and with pool changes
eval {
    PVE::Network::SDN::lock_sdn_domain(sub { PVE::Network::SDN::commit_config() });
};
my $commit_err = $@;
# still apply the running config on this node, but let the unit fail
warn "failed to commit the SDN configuration - $commit_err" if $commit_err;

my $new_config_has_frr = PVE::Network::SDN::running_config_has_frr();
my $regenerate_frr = ($previous_config_has_frr || $new_config_has_frr);

PVE::Network::SDN::generate_etc_network_config();

my $err = sub {
    my $line = shift;
    if ($line =~ /(warning|error): (\S+):/) {
        print "$2 : $line \n";
    }
};

eval { PVE::Tools::run_command(['ifreload', '-a'], errfunc => $err) };
my $ifreload_err = $@;

apply_vrf_ct_zones();

# needs the zone VRFs created by ifreload, because dnsmasq is started inside
# them with 'ip vrf exec'. Also done if ifreload failed, so that a single
# failing interface does not leave the DHCP config of all zones outdated.
eval { PVE::Network::SDN::generate_dhcp_config() };
my $dhcp_err = $@;

if ($ifreload_err) {
    warn "failed to generate the DHCP config - $dhcp_err" if $dhcp_err;
    die $ifreload_err;
}

# the FRR config does not depend on DHCP, keep it in line with the reloaded interfaces
eval { PVE::Network::SDN::generate_frr_config(1) if $regenerate_frr };
my $frr_err = $@;

if ($dhcp_err) {
    warn "failed to regenerate the FRR config - $frr_err" if $frr_err;
    die $dhcp_err;
}
die $frr_err if $frr_err;

exit($commit_err ? 1 : 0);
