#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-or-later
"""Make-before-break PPPoE underlay controller; no commits or global restarts.

All transitions take the normal commit lock. A durable runtime intent allows
restart recovery to roll back an interrupted switch before retiring any link.
"""
import importlib.util
import json
import logging
import os
from pathlib import Path
import subprocess
import time

from vyos.configquery import ConfigTreeQuery
from vyos.pppoe_handover import configured_groups, members, active_member, read_state, write_state, validate
from vyos.utils.commit import acquire_commit_lock_file, release_commit_lock_file
from vyos.vpp_wireguard import resolve_tunnel_addresses

LOG = logging.getLogger('carrier-pppoe-handover')
spec = importlib.util.spec_from_file_location('handover_wg',
    '/usr/libexec/vyos/conf_mode/vpp_interfaces_wireguard.py')
WG = importlib.util.module_from_spec(spec)
spec.loader.exec_module(WG)


def command(*args, timeout=10, check=True):
    return subprocess.run(args, capture_output=True, text=True, timeout=timeout, check=check)


def uptime():
    return float(Path('/proc/uptime').read_text().split()[0])


def ready(member):
    path = Path('/run/vpp-pppoe-client', member + '.json')
    if not path.exists() or not Path('/sys/class/net', member).exists():
        return False
    state = json.loads(path.read_text())
    try:
        from vyos.vpp_pppoe import connection_for
        current = connection_for(member, state['source_interface'])
        return all(state.get(k) == v for k, v in current.items())
    except (OSError, ValueError, RuntimeError):
        return False


def ping(interface, target, vrf=None):
    args = ['ping', '-n', '-c', '2', '-W', '2', '-I', interface, target]
    if vrf:
        args = ['ip', 'vrf', 'exec', vrf] + args
    return command(*args, timeout=6, check=False).returncode == 0


def apply_wg(conf, interfaces):
    previous = os.environ.get('VYOS_TAGNODE_VALUE')
    try:
        for name in interfaces:
            os.environ['VYOS_TAGNODE_VALUE'] = name
            config = WG.get_config(conf)
            config['source_refresh'] = True
            WG.verify(config)
            if 'source_pending' in config:
                raise RuntimeError('Candidate source address is not ready')
            WG.apply(config)
    finally:
        if previous is None:
            os.environ.pop('VYOS_TAGNODE_VALUE', None)
        else:
            os.environ['VYOS_TAGNODE_VALUE'] = previous


def tunnel_health(interfaces):
    for name, config in interfaces.items():
        for peer in config.get('peer', {}).values():
            if 'disable' in peer:
                continue
            targets = resolve_tunnel_addresses(config.get('address', []), peer)
            if not targets:
                raise RuntimeError('No inner peer address for handover verification')
            for target in targets.values():
                if not ping(name, str(target), config.get('vrf')):
                    raise RuntimeError('Tunnel peer did not pass handover verification')


def tick():
    lock, _ = acquire_commit_lock_file()
    if lock is None:
        return
    try:
        conf = ConfigTreeQuery().config
        groups = configured_groups(conf)
        opts = dict(get_first_key=True, key_mangling=('-', '_'), no_tag_node_value_mangle=True)
        clients = conf.get_config_dict(['interfaces', 'pppoe'], **opts)
        tunnels = conf.get_config_dict(['interfaces', 'vpp', 'wireguard'], **opts)
        validate(groups, clients, {n: c for n, c in tunnels.items()
                                  if not c.get('source_group') or c['source_group'] in groups})
        for name, group in groups.items():
            interfaces = {n: c for n, c in tunnels.items()
                          if c.get('source_group') == name and 'disable' not in c}
            if not interfaces:
                continue
            now = uptime()
            current = active_member(name, group)
            state = read_state(name)
            if state.get('rollback'):
                # Both sessions were retained: resume the old source before
                # considering another switch, even if the daemon was killed.
                state['active'] = state['rollback']
                write_state(name, state)
                apply_wg(conf, interfaces)
                state.pop('rollback')
                state['retry_at'] = now + 60
                write_state(name, state)
                continue
            if not state:
                owner = Path('/run/vpp-pppoe-owner', 'pppc' + current[5:] + '.json')
                # Use connection age, not daemon age. Enabling this feature
                # on an old session must not grant it another 36 hours.
                started = json.loads(owner.read_text()).get('started_at', 0) if owner.exists() else 0
                state = dict(active=current, switched_at=min(now, started), status='waiting')
                if not ready(current):
                    state.update(status='starting', starting_at=now)
                write_state(name, state)
            if state.get('status') == 'starting':
                if ready(current):
                    owner = Path('/run/vpp-pppoe-owner', 'pppc' + current[5:] + '.json')
                    started = json.loads(owner.read_text()).get('started_at', now)
                    state.update(switched_at=min(now, started), status='waiting')
                    state.pop('starting_at', None)
                    write_state(name, state)
                elif now - state['starting_at'] < 45:
                    continue  # Allow normal primary negotiation before failover.
            if now < state.get('retry_at', 0):
                continue
            due = now - state['switched_at'] >= int(group.get('rotation_interval', 129600))
            if not due and ready(current):
                continue
            candidate = next(x for x in members(group) if x != current)
            try:
                # Renew ONLY the inactive session to start a fresh lifetime.
                # The PPP callback needs the commit lock: release it while
                # waiting for negotiation, then take a fresh config snapshot.
                command('systemctl', 'restart', 'ppp@' + candidate + '.service')
                release_commit_lock_file(lock)
                lock = None
                deadline = time.monotonic() + 45
                while time.monotonic() < deadline:
                    # Frontend creation precedes address/default-route setup.
                    # Wait for real reachability, not just a named interface.
                    if ready(candidate) and ping(candidate, group['health_check'],
                                                 clients[candidate]['vrf']):
                        break
                    time.sleep(1)
                lock, _ = acquire_commit_lock_file()
                if lock is None:
                    return
                fresh = ConfigTreeQuery().config
                if (configured_groups(fresh) != groups or
                        fresh.get_config_dict(['interfaces', 'pppoe'], **opts) != clients or
                        fresh.get_config_dict(['interfaces', 'vpp', 'wireguard'], **opts) != tunnels):
                    return  # Never act on a stale configuration snapshot.
                conf = fresh
                if not ready(candidate) or not ping(candidate, group['health_check'],
                                                    clients[candidate]['vrf']):
                    raise RuntimeError('Candidate PPPoE health check failed')
                transition = dict(state, active=candidate, rollback=current, status='switching')
                write_state(name, transition)
                try:
                    apply_wg(conf, interfaces)
                    tunnel_health(interfaces)
                except Exception:
                    transition['active'] = current
                    write_state(name, transition)
                    apply_wg(conf, interfaces)
                    # Keep rollback intent until the old source is restored.
                    transition.pop('rollback')
                    transition.update(status='rolled-back', retry_at=uptime() + 60)
                    write_state(name, transition)
                    raise
                state = dict(active=candidate, switched_at=uptime(), status='ready')
                write_state(name, state)
                LOG.info('Group %s switched %s -> %s; old session retained', name, current, candidate)
            except Exception as error:
                # Never expose configuration dictionaries or credential data.
                LOG.warning('Group %s handover deferred (%s)', name, type(error).__name__)
                if lock is None:
                    return
                state = read_state(name)
                state.update(retry_at=uptime() + 60, status='retry')
                write_state(name, state)
    finally:
        if lock is not None:
            release_commit_lock_file(lock)


if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    while True:
        try:
            tick()
        except Exception as error:
            LOG.error('Controller retry (%s)', type(error).__name__)
        time.sleep(5)
