#!/usr/bin/env python3
"""Reconcile the primary LAN with reality (ADR-0022 part 1).

Normally invoked detached by /etc/NetworkManager/dispatcher.d/50-vendora-lan
on interface up/down. Also useful by hand:

    sudo vendora-lan-reconcile          # reconcile if something moved
    sudo vendora-lan-reconcile --force  # re-render even if nothing moved
    sudo vendora-lan-reconcile --status # report only; change nothing

What it does: if the operator's configured LAN interface is missing (the
classic dead USB-Eth), stand the primary LAN up on the eth0.10 mgmt VLAN and
re-render dnsmasq + nftables onto it — so the box stays reachable AND keeps
selling. When the interface returns, tear the fallback down and move back.
lan_iface (the operator's intent) is never modified either way.

Logs to stderr; the dispatcher discards it, so anything worth keeping is also
logged to the journal by the services themselves.
"""
import logging
import sys

sys.path.insert(0, "/opt/vendora_sbc/services")

from common import lan_config as vlan          # noqa: E402
from common import lan_reconcile               # noqa: E402


def main() -> int:
    args = set(sys.argv[1:])
    logging.basicConfig(
        level=logging.INFO,
        format="vendora-lan-reconcile: %(levelname)s %(message)s",
        stream=sys.stderr,
    )

    if "--status" in args or "-s" in args:
        state = vlan.lan_state()
        deployed = lan_reconcile.deployed_primary_iface()
        print("intent:    %s" % state["intent"])
        print("effective: %s" % state["effective"])
        print("deployed:  %s" % (deployed or "<unknown>"))
        print("degraded:  %s%s" % (state["degraded"],
                                   " (%s)" % state["reason"] if state["reason"] else ""))
        return 0

    result = lan_reconcile.reconcile(force=("--force" in args or "-f" in args))
    if result.get("error"):
        return 1
    if result.get("changed"):
        print("reconciled: primary LAN now on %s (intent %s, degraded=%s)"
              % (result.get("effective"), result.get("intent"), result.get("degraded")))
    return 0


if __name__ == "__main__":
    sys.exit(main())
