#!/usr/bin/env python3
#
# Copyright (C) Carrier Router contributors
#
# Migrate the historical WireGuard peer "address" node to the canonical
# "endpoint" node.  The alias existed only to make an in-place VyOS upgrade
# safe; it is deliberately absent from the version-35 interactive CLI.

from vyos.configtree import ConfigTree


BASE = ['interfaces', 'wireguard']


def migrate(config: ConfigTree) -> None:
    if not config.exists(BASE):
        return

    for interface in config.list_nodes(BASE):
        peer_base = BASE + [interface, 'peer']
        if not config.exists(peer_base):
            continue
        for peer in config.list_nodes(peer_base):
            base = peer_base + [peer]
            old_path = base + ['address']
            endpoint_path = base + ['endpoint']
            if not config.exists(old_path):
                continue
            # A canonical endpoint, if already present, always wins.  This also
            # repairs configurations created during the temporary alias period
            # that accidentally contain both nodes.
            if not config.exists(endpoint_path):
                config.set(endpoint_path, value=config.return_value(old_path))
            config.delete(old_path)
