#!/bin/bash
set -euo pipefail

WIFI_IFACE="${WIFI_IFACE:-wlan0}"
ETH_IFACE="eth0"
LEGACY_NETPLAN="/etc/netplan/99-nivato-logger-network-manager.yaml"

# shellcheck source=/dev/null
. /opt/nivato-logger/bin/nivato-progress.sh 2>/dev/null || true

log() {
    if command -v nivato_progress >/dev/null 2>&1 || type nivato_progress >/dev/null 2>&1; then
        nivato_progress INFO "[network] $*"
    else
        echo "[nivato-logger-network] $*"
    fi
}

warn() {
    if command -v nivato_progress >/dev/null 2>&1 || type nivato_progress >/dev/null 2>&1; then
        nivato_progress WARN "[network] $*"
    else
        echo "[nivato-logger-network] UWAGA: $*" >&2
    fi
}

has_command() {
    command -v "$1" >/dev/null 2>&1
}

remove_legacy_netplan() {
    if [ ! -f "$LEGACY_NETPLAN" ]; then
        return 0
    fi

    warn "Usuwam $LEGACY_NETPLAN (stara konfiguracja)..."
    rm -f "$LEGACY_NETPLAN"
}

setup_netplan_nm_renderer() {
    if ! has_command netplan; then
        warn "netplan niedostępne — pomijam konfigurację netplan"
        return 0
    fi

    log "Ustawiam renderer: NetworkManager w netplan dla $ETH_IFACE i $WIFI_IFACE..."

    python3 - "$ETH_IFACE" "$WIFI_IFACE" << 'PYTHON'
import sys
import glob

try:
    import yaml
except ImportError:
    print("python3-yaml niedostępne — pomijam netplan", file=sys.stderr)
    sys.exit(0)

eth_iface, wifi_iface = sys.argv[1], sys.argv[2]
targets = [("ethernets", eth_iface), ("wifis", wifi_iface)]
files = sorted(glob.glob("/etc/netplan/*.yaml"))

for path in files:
    try:
        with open(path) as f:
            data = yaml.safe_load(f)
        if not data or "network" not in data:
            continue
        net = data["network"]
        changed = False
        for section, iface in targets:
            if section not in net or iface not in net[section]:
                continue
            entry = net[section][iface]
            if entry is None:
                entry = {}
                net[section][iface] = entry
            if entry.get("renderer") != "NetworkManager":
                entry["renderer"] = "NetworkManager"
                changed = True
        if changed:
            with open(path, "w") as f:
                yaml.dump(data, f, default_flow_style=False, allow_unicode=True)
            print(f"Zaktualizowano: {path}", file=sys.stderr)
    except Exception as e:
        print(f"Błąd przy {path}: {e}", file=sys.stderr)
PYTHON

    netplan generate 2>/dev/null || warn "netplan generate zwrócił błąd"
    netplan apply || warn "netplan apply nie powiódł się"
}

restart_network_manager() {
    if ! has_command nmcli; then
        warn "nmcli niedostępne — NetworkManager nie jest zainstalowany"
        return 0
    fi

    log "Uruchamiam NetworkManager..."
    systemctl enable NetworkManager 2>/dev/null || true
    systemctl restart NetworkManager

    sleep 2

    log "Status urządzeń:"
    nmcli -t -f DEVICE,TYPE,STATE device status 2>/dev/null | while IFS= read -r line; do
        log "  $line"
    done
}

disable_wait_online() {
    if ! has_command systemctl; then
        return 0
    fi

    log "Wyłączam czekanie na pełną łączność sieciową przy starcie..."
    # Logger startuje offline-first i sam wystawia hotspot konfiguracyjny.
    # Usługi wait-online blokują boot na świeżym urządzeniu bez kabla/WiFi.
    systemctl disable --now systemd-networkd-wait-online.service 2>/dev/null || true
    systemctl disable --now NetworkManager-wait-online.service 2>/dev/null || true
}

set_wifi_regulatory() {
    local domain="${NIVATO_WIFI_REG_DOMAIN:-PL}"
    if has_command iw; then
        log "Ustawiam domenę regulacyjną WiFi: $domain"
        /usr/sbin/iw reg set "$domain" 2>/dev/null || warn "iw reg set $domain nie powiodło się"
    else
        warn "iw niedostępne — pomijam ustawienie domeny regulacyjnej"
    fi
}

main() {
    log "Konfiguracja sieci (NetworkManager dla WiFi i Ethernet)..."
    set_wifi_regulatory
    remove_legacy_netplan
    setup_netplan_nm_renderer
    disable_wait_online
    restart_network_manager
    log "Gotowe."
}

main "$@"
