# 30-network
# prompt for network config, and set it up.

source "$(dirname "${BASH_SOURCE[0]}")/ip_hostname-validation"

FB_CONN_NAME=""
FB_IFACE=""
SELECTED_NIC=""
DATA_CONN_NAME=""
DATA_IFACE=""
DATA_COMBINED=0
DATA_IPV4_CIDR=""
DATA_IPV4_GW=""
DATA_IPV6_ADDR=""
NETWORK_PLANE_FILE="/etc/hybappliance/network/planes.conf"
PROXY_ENABLED=""
PROXY_URL=""
DEFAULT_NO_PROXY="localhost,127.0.0.1,::1,10.42.0.0/16,10.43.0.0/16,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,.svc,.cluster.local,fc00::/7,fe80::/10"

atomic_replace_file() {
    local target="$1" mode="$2" directory temporary
    directory="${target%/*}"
    mkdir -p "$directory" 2>/dev/null || return 1
    if [ -L "$target" ]; then
        log "firstboot: refusing to replace symlink: $target"
        return 1
    fi
    temporary="$(mktemp "$directory/.${target##*/}.XXXXXX")" || return 1
    if ! cat > "$temporary"; then
        rm -f "$temporary"
        return 1
    fi
    chmod "$mode" "$temporary" || {
        rm -f "$temporary"
        return 1
    }
    mv -f "$temporary" "$target"
}

set_connection_profile_name() {
    [ -n "$FB_IFACE" ] && FB_CONN_NAME="$FB_IFACE" || FB_CONN_NAME="slos"
}

set_data_connection_profile_name() {
    [ -n "$DATA_IFACE" ] && DATA_CONN_NAME="data-$DATA_IFACE" || DATA_CONN_NAME=""
}

get_interface_mac() {
    local iface="$1"
    [ -r "/sys/class/net/$iface/address" ] || return 0
    cat "/sys/class/net/$iface/address" 2>/dev/null | tr -d '[:space:]'
}

discovered_interface_count() {
    if [ -s "$NIC_DISCOVERY_FILE" ]; then
        awk -F'|' '$1 != "" && $1 != "lo" { count++ } END { print count + 0 }' "$NIC_DISCOVERY_FILE"
    else
        echo 1
    fi
}

persist_network_plane_config() {
    local config_dir config_tmp management_mac data_mac

    config_dir="${NETWORK_PLANE_FILE%/*}"
    config_tmp=""
    management_mac="$(get_interface_mac "$FB_IFACE")"
    data_mac="$(get_interface_mac "$DATA_IFACE")"

    mkdir -p "$config_dir" 2>/dev/null || return 1
    config_tmp="$(mktemp "${config_dir}/.planes.conf.XXXXXX")" || return 1
    if ! {
        printf 'MANAGEMENT_INTERFACE=%q\n' "$FB_IFACE"
        printf 'MANAGEMENT_MAC=%q\n' "$management_mac"
        printf 'MANAGEMENT_CONNECTION=%q\n' "$FB_CONN_NAME"
        if [ "$DATA_COMBINED" = "1" ]; then
            printf 'DATA_INTERFACE=%q\n' "$FB_IFACE"
            printf 'DATA_MAC=%q\n' "$management_mac"
            printf 'DATA_CONNECTION=%q\n' "$FB_CONN_NAME"
        else
            printf 'DATA_INTERFACE=%q\n' "$DATA_IFACE"
            printf 'DATA_MAC=%q\n' "$data_mac"
            printf 'DATA_CONNECTION=%q\n' "$DATA_CONN_NAME"
        fi
        printf 'DATA_IP=%q\n' "$DATA_IPV4_CIDR"
        printf 'DATA_GATEWAY=%q\n' "$DATA_IPV4_GW"
        printf 'DATA_ROUTE_TABLE=200\n'
        if [ "$DATA_COMBINED" = "1" ]; then
            printf 'DATA_STATUS=combined\n'
        elif [ -n "$DATA_IFACE" ]; then
            printf 'DATA_STATUS=configured\n'
        elif [ "$(discovered_interface_count)" -le 1 ]; then
            printf 'DATA_STATUS=combined\n'
        else
            printf 'DATA_STATUS=deferred\n'
        fi
    } > "$config_tmp"; then
        rm -f "$config_tmp"
        return 1
    fi
    chmod 644 "$config_tmp" 2>/dev/null || true
    [ ! -L "$NETWORK_PLANE_FILE" ] || {
        rm -f "$config_tmp"
        return 1
    }
    mv -f "$config_tmp" "$NETWORK_PLANE_FILE"
    log "firstboot:network: persisted management=$FB_IFACE data=${DATA_IFACE:-deferred}"
}

format_nic_speed() {
    local speed_file="$1"
    local raw_speed=""

    if [ -r "$speed_file" ] ; then
        raw_speed="$(cat "$speed_file" 2>/dev/null | tr -d '[:space:]')"
    fi

    case "$raw_speed" in
        1000)  echo "1Gbps" ;;
        10000) echo "10Gbps" ;;
        25000) echo "25Gbps" ;;
        ""|-1) echo "N/A" ;;
        *)     echo "N/A" ;;
    esac
}

format_nic_menu_desc() {
    local driver="$1"
    local mac="$2"
    local speed="$3"

    [ -n "$driver" ] || driver="n/a"
    [ -n "$mac" ] || mac="n/a"
    [ -n "$speed" ] || speed="n/a"

    # Keep menu rows compact and aligned so fields do not visually overlap.
    [ ${#driver} -gt 12 ] && driver="${driver:0:11}~"
    [ ${#mac} -gt 17 ] && mac="${mac:0:16}~"
    [ ${#speed} -gt 10 ] && speed="${speed:0:9}~"

    printf 'drv:%-12s mac:%-17s spd:%s' \
        "$driver" "$mac" "$speed"
}

show_network_scan_notice() {
    $DIALOG \
        --clear \
        --backtitle "$BT" \
        --title "Network Scan" \
        --infobox "\nScanning network interfaces, please wait...\n" \
        $H1 $W1
}

discover_network_interfaces() {
    local iface_path iface_name addr_path mac driver_path driver_target driver_name speed_name
    local scan_attempt module module_list interface_count selinux_mode module_root
    local -a known_nic_modules=(e1000e igb tg3 r8169 ixgbe i40e ice bnx2 vmxnet3 virtio_net)
    NIC_DISCOVERY_FILE="/tmp/firstboot.nic.discovery.$$"
    : > "$NIC_DISCOVERY_FILE"

    # Probe the appliance's known NIC modules before triggering udev. This is
    # deterministic and also works when lspci does not report a module.
    for module in "${known_nic_modules[@]}" ; do
        modprobe "$module" >/dev/null 2>&1 || true
    done

    # Trigger the parent PCI bus to match vendor/device IDs and load modules.
    udevadm trigger --subsystem-match=pci --action=add >/dev/null 2>&1
    # Trigger network subsystem updates for newly discovered devices.
    udevadm trigger --subsystem-match=net --action=add >/dev/null 2>&1
    udevadm settle --timeout=15 >/dev/null 2>&1

    # Restore module labels and repeat the known-module probe when SELinux can
    # interfere with loading a newly attached adapter's driver.
    selinux_mode="$(getenforce 2>/dev/null)"
    case "$selinux_mode" in
    Enforcing|Permissive)
        for module_root in \
            /usr/lib/modules \
            "/usr/lib/modules/$(uname -r)" \
            /lib/modules \
            "/lib/modules/$(uname -r)" ; do
            [ -e "$module_root" ] || continue
            restorecon -RF "$module_root" >/dev/null 2>&1 || true
        done
        for module in "${known_nic_modules[@]}" ; do
            modprobe "$module" >/dev/null 2>&1 || true
        done
        ;;
    esac

    # Probe any additional driver advertised by PCI as a fallback.
    module_list="$(lspci -k 2>/dev/null | awk '/^[[:space:]]*Kernel modules:/{sub(/^[[:space:]]*Kernel modules:[[:space:]]*/, ""); gsub(/,/, "\n"); print}')"
    while IFS= read -r module ; do
        [ -n "$module" ] || continue
        modprobe "$module" >/dev/null 2>&1 || true
    done <<< "$module_list"

    # Give udev and NetworkManager several opportunities to expose adapters
    # before treating the machine as single-interface.
    for scan_attempt in 1 2 3 4 5 ; do
        : > "$NIC_DISCOVERY_FILE"
        for iface_path in /sys/class/net/* ; do
            iface_name="${iface_path##*/}"
            case "$iface_name" in
                .|..|lo) continue ;;
            esac

            addr_path="$iface_path/address"
            [ -e "$addr_path" ] || continue

            mac="$(cat "$addr_path" 2>/dev/null | tr -d '[:space:]')"
            [ -n "$mac" ] || mac=""

            driver_name=""
            driver_path="$iface_path/device/driver"
            if [ -L "$driver_path" ] ; then
                driver_target="$(readlink "$driver_path" 2>/dev/null)"
                [ -n "$driver_target" ] && driver_name="$(basename "$driver_target")"
            fi

            speed_name="$(format_nic_speed "$iface_path/speed")"
            printf '%s|%s|%s|%s\n' "$iface_name" "$driver_name" "$mac" "$speed_name" >> "$NIC_DISCOVERY_FILE"
        done

        interface_count="$(discovered_interface_count)"
        [ "$interface_count" -gt 1 ] && break
        sleep 1
    done

    sort -t '|' -k1,1 "$NIC_DISCOVERY_FILE" -o "$NIC_DISCOVERY_FILE"
    [ -s "$NIC_DISCOVERY_FILE" ]
}

get_first_discovered_interface() {
    [ -s "$NIC_DISCOVERY_FILE" ] || return 1
    head -n 1 "$NIC_DISCOVERY_FILE" | cut -d '|' -f 1
}

bring_interfaces_to_selected_state() {
    local selected="$1"
    local iface_path iface_name

    [ -n "$selected" ] || return 1

    for iface_path in /sys/class/net/* ; do
        iface_name="${iface_path##*/}"
        case "$iface_name" in
            .|..|lo) continue ;;
        esac
        [ "$iface_name" = "$selected" ] && continue
        ip link set "$iface_name" down 2>/dev/null
    done

    ip link set "$selected" up >> "$LOG" 2>&1
}

disable_nonselected_autoconnect() {
    local selected="$1"
    local conn_name conn_type conn_ifname

    [ -n "$selected" ] || return 1

    nmcli -t -f NAME,TYPE connection show 2>/dev/null | while IFS=: read -r conn_name conn_type ; do
        [ -n "$conn_name" ] || continue
        [ "$conn_type" = "802-3-ethernet" ] || continue

        conn_ifname="$(nmcli -g connection.interface-name connection show "$conn_name" 2>/dev/null | head -n 1)"

        if [ -z "$conn_ifname" ] || [ "$conn_ifname" != "$selected" ] ; then
            nmcli con mod "$conn_name" connection.autoconnect no >> "$LOG" 2>&1 || true
        fi
    done
}

install_nm_ethernet_profile_namer() {
    local dispatcher_dir="/etc/NetworkManager/dispatcher.d"
    local script_path="$dispatcher_dir/92-ethernet-profile-name"

    [ -d "$dispatcher_dir" ] || mkdir -p "$dispatcher_dir" >/dev/null 2>&1 || return 0

    cat > "$script_path" <<'EOF'
#!/usr/bin/bash
# Rename only default auto-named ethernet profiles ("Wired connection *")
# to interface names (eth0/eth1/...), keeping existing named profiles intact.
IFACE="$1"
ACTION="$2"
active_uuid=""
conn_name=""
conn_ifname=""

case "$ACTION" in
    up|dhcp4-change|dhcp6-change|connectivity-change|reapply) ;;
    *) exit 0 ;;
esac

[ -n "$IFACE" ] || exit 0
[ "$IFACE" = "lo" ] && exit 0

active_uuid="$(nmcli -t -f UUID,TYPE,DEVICE connection show --active 2>/dev/null | awk -F: -v dev="$IFACE" '$3 == dev && ($2 == "802-3-ethernet" || $2 == "ethernet") { print $1; exit }')"
[ -n "$active_uuid" ] || exit 0

conn_name="$(nmcli -g connection.id connection show uuid "$active_uuid" 2>/dev/null | head -n 1)"
[ -n "$conn_name" ] || exit 0

# Do not touch profiles explicitly bound to another interface.
conn_ifname="$(nmcli -g connection.interface-name connection show uuid "$active_uuid" 2>/dev/null | head -n 1)"
if [ -n "$conn_ifname" ] && [ "$conn_ifname" != "$IFACE" ] ; then
    exit 0
fi

case "$conn_name" in
    "Wired connection"*|"Wired network"*) ;;
    *) exit 0 ;;
esac

# Do not rename if an interface-named profile already exists.
if nmcli -t -f NAME connection show 2>/dev/null | grep -Fqx "$IFACE" ; then
    exit 0
fi

nmcli connection modify uuid "$active_uuid" connection.id "$IFACE" connection.interface-name "$IFACE" >/dev/null 2>&1 || exit 0
exit 0
EOF

    chmod 755 "$script_path" >/dev/null 2>&1 || true
    if command -v restorecon >/dev/null 2>&1 ; then
        restorecon "$script_path" >/dev/null 2>&1 || true
    fi
}

rename_saved_nm_ethernet_profiles() {
    local uuid conn_type conn_name conn_ifname

    while IFS=: read -r uuid conn_type ; do
        [ -n "$uuid" ] || continue
        case "$conn_type" in
            802-3-ethernet|ethernet) ;;
            *) continue ;;
        esac

        conn_name="$(nmcli -g connection.id connection show uuid "$uuid" 2>/dev/null | head -n 1)"
        conn_ifname="$(nmcli -g connection.interface-name connection show uuid "$uuid" 2>/dev/null | head -n 1)"
        [ -n "$conn_name" ] || continue
        [ -n "$conn_ifname" ] || continue
        [ "$conn_ifname" = "lo" ] && continue

        case "$conn_name" in
            "Wired connection"*|"Wired network"*) ;;
            *) continue ;;
        esac

        if nmcli -t -f NAME connection show 2>/dev/null | grep -Fqx "$conn_ifname" ; then
            continue
        fi

        nmcli connection modify uuid "$uuid" connection.id "$conn_ifname" >> "$LOG" 2>&1 || true
    done <<EOF
$(nmcli -t -f UUID,TYPE connection show 2>/dev/null)
EOF
}

select_firstboot_interface() {
    local default_iface iface driver mac speed
    local -a nic_menu_items

    show_network_diagnostics() {
        local diag_file="/tmp/firstboot.nic.diag.$$"
        local diag_modules_disabled=""

        [ -r /proc/sys/kernel/modules_disabled ] && diag_modules_disabled="$(cat /proc/sys/kernel/modules_disabled 2>/dev/null)"

        {
            echo "=== Network Diagnostics ==="
            echo
            echo "kernel.modules_disabled: ${diag_modules_disabled:-Unknown}"
            echo
            if [ "$diag_modules_disabled" = "1" ] ; then
                echo "POSSIBLE ROOT CAUSE: kernel.modules_disabled=1 (runtime module loading blocked)."
                echo
            fi
            echo "ip link show"
            ip link show 2>&1
            echo
            echo "dmesg | grep -iE 'eth|enp|ens|net'"
            dmesg | grep -iE 'eth|enp|ens|net' 2>&1
        } > "$diag_file"

        $DIALOG --backtitle "$BT" --title "Network Diagnostics" --textbox "$diag_file" $H1 $W1
        rm -f "$diag_file" 2>/dev/null || true
    }

    while true ; do
        SCAN_FLAG="/tmp/firstboot.scan.running.$$"
        touch "$SCAN_FLAG"
        (
            while [ -f "$SCAN_FLAG" ] ; do
                $DIALOG \
                    --backtitle "$BT" \
                    --title "Network Scan" \
                    --infobox "\nScanning network interfaces.\n" \
                    $H1 $W1
                sleep 2
            done
        ) &
        DIALOG_PID=$!

        discover_network_interfaces
        DISCOVER_RC=$?

        rm -f "$SCAN_FLAG"
        wait $DIALOG_PID 2>/dev/null || true
        clear

        if [ $DISCOVER_RC -eq 0 ] ; then
            :
        else
            log "firstboot:network: no network interfaces discovered; continuing without network selection"
            return 1
        fi

        nic_menu_items=()
        while IFS='|' read -r iface driver mac speed ; do
            nic_menu_items+=("$iface" "$(format_nic_menu_desc "$driver" "$mac" "$speed")")
        done < "$NIC_DISCOVERY_FILE"

        default_iface="$FB_IFACE"
        [ -n "$default_iface" ] || default_iface="$(get_first_discovered_interface)"

        $DIALOG \
            --clear \
            --visit-items \
            --backtitle "$BT" \
            --title "Select Management Interface" \
            --ok-label "Next" \
            --extra-button \
            --extra-label "Back" \
            --nocancel \
            --default-item "$default_iface" \
            --menu "\nSelect the interface for management traffic.\n" \
            $H1 $W1 12 \
            "${nic_menu_items[@]}" \
            2>"$tempfile"

        [ "$?" = "3" ] && {
            BACK_TO="40-hostname"
            return 1
        }

        SELECTED_NIC="$(cat "$tempfile")"
        [ -n "$SELECTED_NIC" ] || continue

        FB_IFACE="$SELECTED_NIC"
        set_connection_profile_name
        bring_interfaces_to_selected_state "$SELECTED_NIC"
        log "firstboot:network: selected interface=$FB_IFACE profile=$FB_CONN_NAME"
        return 0
    done
}

select_data_interface() {
    local iface driver mac speed dialog_status
    local -a data_menu_items

    if [ "$(grep -v "^$FB_IFACE|" "$NIC_DISCOVERY_FILE" 2>/dev/null | wc -l)" -eq 0 ]; then
        DATA_IFACE=""
        DATA_CONN_NAME=""
        log "firstboot:network: only one interface discovered; data plane deferred"
        return 0
    fi

    data_menu_items=("combined" "Use the management interface for combined traffic" "defer" "Configure the data plane later")
    while IFS='|' read -r iface driver mac speed ; do
        [ "$iface" = "$FB_IFACE" ] && continue
        data_menu_items+=("$iface" "$(format_nic_menu_desc "$driver" "$mac" "$speed" "$iface")")
    done < "$NIC_DISCOVERY_FILE"

    $DIALOG \
        --clear \
        --visit-items \
        --backtitle "$BT" \
            --title "Data Plane Interface" \
        --ok-label "Next" \
        --extra-button \
        --extra-label "Back" \
        --nocancel \
        --default-item "defer" \
            --menu "\nSelect the interface for data-plane traffic.\n\nData-plane configuration can be deferred until the data network is available.\n" \
        $H1 $W1 12 \
        "${data_menu_items[@]}" \
        2>"$tempfile"
    dialog_status="$?"

    [ "$dialog_status" = "3" ] && {
        BACK_TO="40-hostname"
        return 1
    }

    DATA_IFACE="$(cat "$tempfile")"
    if [ "$DATA_IFACE" = "combined" ]; then
        DATA_IFACE=""
        DATA_CONN_NAME=""
        DATA_COMBINED=1
        log "firstboot:network: combined management and data traffic selected"
        return 0
    fi
    if [ "$DATA_IFACE" = "defer" ] || [ -z "$DATA_IFACE" ]; then
        DATA_IFACE=""
        DATA_CONN_NAME=""
        DATA_COMBINED=0
        log "firstboot:network: data plane setup deferred"
        return 0
    fi

    set_data_connection_profile_name
    ip link set "$DATA_IFACE" up >> "$LOG" 2>&1 || true
    log "firstboot:network: selected data interface=$DATA_IFACE profile=$DATA_CONN_NAME"
    return 0
}

mask_to_prefix() {
    local mask="$1"
    local prefix

    if echo "$mask" | grep -Eq '^[0-9]+$' ; then
        [ "$mask" -ge 0 ] && [ "$mask" -le 32 ] && echo "$mask" && return 0
        return 1
    fi

    prefix=$(echo "$mask" | awk -F. '
        NF!=4 { print -1; exit }
        {
            seen_zero=0
            c=0
            for (i=1; i<=4; i++) {
                if ($i !~ /^[0-9]+$/ || $i < 0 || $i > 255) { print -1; exit }
                v=$i
                for (b=7; b>=0; b--) {
                    bit = and(v, lshift(1,b)) ? 1 : 0
                    if (bit == 1) {
                        if (seen_zero) { print -1; exit }
                        c++
                    } else {
                        seen_zero=1
                    }
                }
            }
            print c+0
        }')

    [ "$prefix" -ge 0 ] 2>/dev/null || return 1
    echo "$prefix"
    return 0
}

ensure_firstboot_connection() {
    set_connection_profile_name
    install_nm_ethernet_profile_namer
    rename_saved_nm_ethernet_profiles

    # Remove stale legacy fixed profile once interface-specific profile is in use.
    if [ "$FB_CONN_NAME" != "slos" ] && nmcli -t -f NAME connection show 2>/dev/null | grep -qx "slos" ; then
        log "firstboot:network: removing legacy profile slos"
        nmcli con delete "slos" >> "$LOG" 2>&1 || true
    fi

    if ! nmcli -t -f NAME connection show 2>/dev/null | grep -qx "$FB_CONN_NAME" ; then
        log "firstboot:network: creating connection $FB_CONN_NAME on $FB_IFACE"
        nmcli con add con-name "$FB_CONN_NAME" ifname "$FB_IFACE" type ethernet >> "$LOG" 2>&1
    else
        log "firstboot:network: using existing connection $FB_CONN_NAME"
        nmcli con mod "$FB_CONN_NAME" connection.interface-name "$FB_IFACE" >> "$LOG" 2>&1
    fi

    # Keep only the selected NIC enabled by default; users can re-enable others later.
    disable_nonselected_autoconnect "$FB_IFACE"
    nmcli con mod "$FB_CONN_NAME" connection.autoconnect yes >> "$LOG" 2>&1 || true
}

ensure_data_connection() {
    [ -n "$DATA_IFACE" ] || return 1
    set_data_connection_profile_name

    if ! timeout 15 nmcli -t -f NAME connection show 2>/dev/null | grep -qx "$DATA_CONN_NAME" ; then
        timeout 15 nmcli con add con-name "$DATA_CONN_NAME" ifname "$DATA_IFACE" type ethernet >> "$LOG" 2>&1 || return 1
    else
        timeout 15 nmcli con mod "$DATA_CONN_NAME" connection.interface-name "$DATA_IFACE" >> "$LOG" 2>&1 || return 1
    fi

    timeout 15 nmcli con mod "$DATA_CONN_NAME" connection.autoconnect yes \
        ipv4.never-default yes ipv4.ignore-auto-dns yes \
        ipv6.never-default yes ipv6.ignore-auto-dns yes >> "$LOG" 2>&1
}

collect_data_ipv4_details() {
    local ipv4_cidr ipv4_addr ipv4_mask ipv4_gw prefix
    local d_ipv4_cidr d_ipv4_gw confirm

    d_ipv4_cidr="$DATA_IPV4_CIDR"
    d_ipv4_gw="$DATA_IPV4_GW"

    while true ; do
        $DIALOG \
            --clear \
            --visit-items \
            --backtitle "$BT" \
            --title "Data Plane Network Address" \
            --ok-label "Next" \
            --extra-button \
            --extra-label "Back" \
            --nocancel \
            --form "\nEnter the data-plane IPv4 address and gateway.\n\nUse CIDR notation for the address.\nExample address: 10.20.30.15/24\nExample gateway: 10.20.30.1\n\n[Tab: Move between fields | Enter: Continue]\n" \
            $H1 $W1 12 \
            "Data-plane IP / prefix" 1 1 "$d_ipv4_cidr" 1 27 27 39 \
            "Data-plane gateway" 2 1 "$d_ipv4_gw" 2 27 27 39 \
            2>"$tempfile"

        [ "$?" = "3" ] && return 1
        ipv4_cidr=$(trim_ws "$(sed -n '1p' "$tempfile")")
        ipv4_gw=$(trim_ws "$(sed -n '2p' "$tempfile")")
        d_ipv4_cidr="$ipv4_cidr"
        d_ipv4_gw="$ipv4_gw"

        ipv4_addr="${ipv4_cidr%%/*}"
        ipv4_mask="${ipv4_cidr#*/}"
        if [ "$ipv4_cidr" = "$ipv4_addr" ] || [ -z "$ipv4_addr" ] || [ -z "$ipv4_mask" ] ; then
            $DIALOG --backtitle "$BT" --title "Invalid Network Address" --msgbox "\nEnter the data-plane address in CIDR notation.\n\nExample: 10.20.30.15/24\n" $H1 $W1
            continue
        fi

        if ! is_valid_ipv4_addr "$ipv4_addr" || ! is_valid_ipv4_addr "$ipv4_gw" ; then
            $DIALOG --backtitle "$BT" --title "Invalid Network Address" --msgbox "\nEnter a valid data-plane IPv4 address and gateway.\n\nAddress example: 10.20.30.15/24\nGateway example: 10.20.30.1\n" $H1 $W1
            continue
        fi

        prefix="$(mask_to_prefix "$ipv4_mask")" || {
            $DIALOG --backtitle "$BT" --title "Invalid Subnet Prefix" --msgbox "\nThe IPv4 subnet prefix must be between 0 and 32.\n\nExample: /24 represents 255.255.255.0.\n" $H1 $W1
            continue
        }

        confirm="$($DIALOG --clear --backtitle "$BT" --title "Confirm Data Plane Configuration" --yesno "\nReview the data-plane configuration before applying it.\n\nIPv4 address: $ipv4_addr/$prefix\nGateway:      $ipv4_gw\nRouting:      Data-plane traffic only\n\nSelect Yes to apply these settings or No to return to the form." $H1 $W1; echo $?)"
        [ "$confirm" = "0" ] || continue
        DATA_IPV4_CIDR="$ipv4_addr/$prefix"
        DATA_IPV4_GW="$ipv4_gw"
        return 0
    done
}

apply_data_dhcp_network() {
    ensure_data_connection || return 1
    timeout 15 nmcli con mod "$DATA_CONN_NAME" \
        ipv4.method auto ipv4.addresses "" ipv4.gateway "" ipv4.dns "" \
        ipv4.never-default no ipv4.route-table 200 ipv4.ignore-auto-dns yes \
        ipv6.method auto ipv6.addresses "" ipv6.gateway "" ipv6.dns "" \
        ipv6.never-default yes ipv6.ignore-auto-dns yes >> "$LOG" 2>&1 || return 1
    nmcli -w 3 con up "$DATA_CONN_NAME" >> "$LOG" 2>&1 || return 1
    local lease source
    lease="$(nmcli -g IP4.ADDRESS device show "$DATA_IFACE" 2>/dev/null | head -n 1)"
    source="${lease%%/*}"
    [ -n "$source" ] || return 1
    timeout 15 nmcli con mod "$DATA_CONN_NAME" ipv4.routing-rules "priority 100 from $source/32 table 200" >> "$LOG" 2>&1 || return 1
    nmcli -w 3 con up "$DATA_CONN_NAME" >> "$LOG" 2>&1 || return 1
    return 0
}

apply_data_static_network() {
    ensure_data_connection || return 1
    timeout 15 nmcli con mod "$DATA_CONN_NAME" \
        ipv4.method manual ipv4.addresses "$DATA_IPV4_CIDR" ipv4.gateway "$DATA_IPV4_GW" ipv4.dns "" \
        ipv4.never-default no ipv4.route-table 200 ipv4.routing-rules "priority 100 from ${DATA_IPV4_CIDR%%/*}/32 table 200" ipv4.ignore-auto-dns yes \
        ipv6.method disabled ipv6.addresses "" ipv6.gateway "" ipv6.dns "" \
        ipv6.never-default yes ipv6.ignore-auto-dns yes >> "$LOG" 2>&1 || return 1
    nmcli -w 3 con up "$DATA_CONN_NAME" >> "$LOG" 2>&1 || return 1
    return 0
}

show_data_network_apply_notice() {
    $DIALOG \
        --clear \
        --backtitle "$BT" \
        --title "Applying Data Plane Configuration" \
        --infobox "\nApplying the data-plane network configuration.\n" \
        $H1 $W1
}

configure_data_plane() {
    local data_mode

    if [ "$DATA_COMBINED" = "1" ]; then
        persist_network_plane_config || log "firstboot:network: failed to persist combined data plane"
        return 0
    fi

    [ -n "$DATA_IFACE" ] || {
        persist_network_plane_config || log "firstboot:network: failed to persist deferred data plane"
        return 0
    }

    $DIALOG \
        --clear \
        --visit-items \
        --backtitle "$BT" \
        --title "Data Plane Setup" \
        --ok-label "Next" \
        --extra-button \
        --extra-label "Defer" \
        --nocancel \
        --menu "\nSelect how the data-plane interface receives its IPv4 address.\n" \
        $H1 $W1 8 \
        1 "Static IP Configuration" \
        2 "Automatic IP Configuration (DHCP)" \
        2>"$tempfile"
    if [ "$?" = "3" ]; then
        DATA_IFACE=""
        DATA_CONN_NAME=""
        persist_network_plane_config || log "firstboot:network: failed to persist deferred data plane"
        return 0
    fi

    data_mode="$(cat "$tempfile")"
    case "$data_mode" in
        1)
            collect_data_ipv4_details || return 0
            show_data_network_apply_notice
            apply_data_static_network || log "firstboot:network: failed to apply data-plane static configuration"
            ;;
        2)
            show_data_network_apply_notice
            apply_data_dhcp_network || log "firstboot:network: failed to apply data-plane DHCP configuration"
            ;;
        *)
            DATA_IFACE=""
            DATA_CONN_NAME=""
            ;;
    esac
    persist_network_plane_config || log "firstboot:network: failed to persist data-plane configuration"
}

show_continue_notice() {
    log "Network saved. Continuing firstboot..."
    sleep 1
}

proxy_value_for_file() {
    printf "'%s'" "$PROXY_URL"
}

no_proxy_value_for_file() {
    printf "'%s'" "$DEFAULT_NO_PROXY"
}

update_proxy_file() {
    local file="$1" style="$2" tmp quoted no_proxy_quoted
    tmp=""
    mkdir -p "$(dirname "$file")" 2>/dev/null || return 1

    [ ! -L "$file" ] || return 1
    tmp="$(mktemp "$(dirname "$file")/.${file##*/}.XXXXXX")" || return 1

    if [ -f "$file" ] ; then
        awk '!/^[[:space:]]*(export[[:space:]]+)?(HTTP_PROXY|HTTPS_PROXY|http_proxy|https_proxy|NO_PROXY|no_proxy)[[:space:]]*=/' "$file" > "$tmp" || return 1
    else
        : > "$tmp" || return 1
    fi

    if [ "$PROXY_ENABLED" = "yes" ] ; then
        quoted="$(proxy_value_for_file)"
        no_proxy_quoted="$(no_proxy_value_for_file)"
        if [ "$style" = "export" ] ; then
            printf 'export HTTP_PROXY=%s\nexport HTTPS_PROXY=%s\nexport http_proxy=%s\nexport https_proxy=%s\n' \
                "$quoted" "$quoted" "$quoted" "$quoted" >> "$tmp"
            printf 'export NO_PROXY=%s\nexport no_proxy=%s\n' "$no_proxy_quoted" "$no_proxy_quoted" >> "$tmp"
        else
            printf 'HTTP_PROXY=%s\nHTTPS_PROXY=%s\nhttp_proxy=%s\nhttps_proxy=%s\n' \
                "$quoted" "$quoted" "$quoted" "$quoted" >> "$tmp"
            printf 'NO_PROXY=%s\nno_proxy=%s\n' "$no_proxy_quoted" "$no_proxy_quoted" >> "$tmp"
        fi
    fi

    chmod 600 "$tmp" || {
        rm -f "$tmp"
        return 1
    }
    mv -f "$tmp" "$file"
}

persist_proxy_settings() {
    local file

    for file in /etc/default/rke2-server /etc/default/rke2-agent /etc/environment ; do
        update_proxy_file "$file" default || return 1
    done
    update_proxy_file /root/.bashrc export || return 1
    persist_proxy_json || return 1
    log "firstboot:network: proxy settings $([ "$PROXY_ENABLED" = "yes" ] && echo enabled || echo disabled)"
}

persist_proxy_json() {
    local json_file="/etc/hybappliance/proxy/httpClientProxy.json"
    local json_tmp authority host port scheme

    sudo /usr/bin/mkdir -p /etc/hybappliance/proxy 2>/dev/null || return 1

    if [ "$PROXY_ENABLED" != "yes" ]; then
        sudo /usr/bin/rm -f "$json_file" 2>/dev/null || return 1
        return 0
    fi

    authority="${PROXY_URL#*://}"
    authority="${authority##*@}"
    scheme="${PROXY_URL%%://*}"

    if [[ "$authority" == *":"* ]] ; then
        host="${authority%%:*}"
        port="${authority##*:}"
    else
        host="$authority"
        port=""
    fi

    [ -n "$port" ] || port=8080

    json_tmp="/tmp/httpClientProxy.json.firstboot.$$"
    printf '[\n  {\n    "host": "%s",\n    "port": %s\n  }\n]\n' \
        "$host" "$port" > "$json_tmp" || return 1
    atomic_replace_file "$json_file" 600 < "$json_tmp"
    rm -f "$json_tmp"
}

configure_proxy() {
    local proxy_choice proxy_value canonical_proxy_value dialog_status proxy_interrupted
    proxy_interrupted=0

    trap 'proxy_interrupted=1' INT
    $DIALOG \
        --clear \
        --visit-items \
        --backtitle "$BT" \
        --title "Proxy Configuration" \
        --ok-label "Next" \
        --extra-button \
        --extra-label "Back" \
        --nocancel \
        --default-item proxy \
        --separate-output \
            --checklist "\nSelect this option to configure an HTTP/HTTPS proxy for update and management services.\n" \
        $H1 $W1 4 \
        proxy "Use HTTP/HTTPS proxy" "off" \
        2>"$tempfile"
    dialog_status="$?"
    trap '' INT

    if [ "$dialog_status" = "3" ] || [ "$dialog_status" = "130" ] || [ "$proxy_interrupted" = "1" ] ; then
        BACK_TO="40-hostname"
        return 1
    fi
    proxy_choice="$(cat "$tempfile")"
    if echo "$proxy_choice" | grep -q 'proxy' ; then
        while true ; do
            proxy_interrupted=0
            trap 'proxy_interrupted=1' INT
            $DIALOG \
                --clear \
                --visit-items \
                --backtitle "$BT" \
                --title "Proxy Configuration" \
                --ok-label "Submit" \
                --extra-button \
                --extra-label "Back" \
                --nocancel \
                --inputbox "\nEnter the HTTP/HTTPS proxy URL.\nAuthentication is optional. The default port is 8080.\n\nExample: https://proxy.example.com:8080\n" \
                $H1 $W1 "${PROXY_URL}" 2>"$tempfile"
            dialog_status="$?"
            trap '' INT

            if [ "$dialog_status" = "3" ] || [ "$dialog_status" = "130" ] || [ "$proxy_interrupted" = "1" ] ; then
                BACK_TO="40-hostname"
                return 1
            fi
            proxy_value="$(trim_ws "$(cat "$tempfile")")"
            canonical_proxy_value="$(canonical_proxy_url "$proxy_value")"
            if [ $? -eq 0 ] ; then
                PROXY_ENABLED="yes"
                PROXY_URL="$canonical_proxy_value"
                return 0
            fi
            $DIALOG --backtitle "$BT" --title "Invalid Proxy URL" \
                --msgbox "\nEnter a complete HTTP or HTTPS proxy URL.\n\nExample: https://proxy.example.com:8080\n" $H1 $W1
        done
    fi

    PROXY_ENABLED="no"
    PROXY_URL=""
    return 0
}

configure_ntp_server() {
    local chrony_conf="/etc/chrony.conf"
    local ntp_default ntp_server ntp_tmp

    ntp_default="$(awk '$1 == "server" || $1 == "pool" { print $2; exit }' \
        "$chrony_conf" 2>/dev/null)"
    [ -n "$ntp_default" ] || ntp_default="ntp.webwasher.com"

    while true ; do
        $DIALOG \
            --clear \
            --backtitle "$BT" \
            --title "NTP Server Configuration" \
            --ok-label "Submit" \
            --extra-button \
            --extra-label "Back" \
            --nocancel \
            --inputbox "\nEnter the NTP server hostname or IP address.\n\nAccurate time is required for secure operation.\n\nExample: pool.ntp.org or 192.168.1.1\n" \
            $H1 $W1 "$ntp_default" 2>"$tempfile"

        ntp_dialog_rc="$?"
        if [ "$ntp_dialog_rc" = "3" ] ; then
            log "firstboot:network: user selected Back from NTP configuration"
            return 2
        elif [ "$ntp_dialog_rc" != "0" ] ; then
            return 1
        fi
        ntp_server="$(cat "$tempfile")"

        if ! is_valid_ntp_server "$ntp_server" ; then
            $DIALOG --backtitle "$BT" --title "Invalid NTP Server" \
                --msgbox "\nEnter a valid NTP server hostname or IP address.\n\nExamples: pool.ntp.org or 192.168.1.1\n" $H1 $W1
            continue
        fi

        [ ! -L "$chrony_conf" ] || return 1
        ntp_tmp="$(mktemp "$(dirname "$chrony_conf")/.chrony.conf.XXXXXX")" || return 1
        if [ -f "$chrony_conf" ] ; then
            awk -v server="$ntp_server" '
                BEGIN { replaced = 0 }
                !replaced && ($1 == "server" || $1 == "pool") {
                    print "server " server
                    replaced = 1
                    next
                }
                { print }
                END {
                    if (!replaced) print "server " server
                }
            ' "$chrony_conf" > "$ntp_tmp" && chmod 644 "$ntp_tmp" && mv -f "$ntp_tmp" "$chrony_conf"
        else
            printf 'server %s\n' "$ntp_server" > "$ntp_tmp" && chmod 644 "$ntp_tmp" && mv -f "$ntp_tmp" "$chrony_conf"
        fi
        rm -f "$ntp_tmp"
        log "firstboot:network: NTP server added during manual configuration: $ntp_server"
        systemctl try-restart chronyd >> "$LOG" 2>&1 || true
        return 0
    done
}

setup_dhcp_network() {
    log "firstboot:network: configuring DHCP on $FB_CONN_NAME/$FB_IFACE"
    ensure_firstboot_connection
    nmcli con mod "$FB_CONN_NAME" ipv4.method auto ipv4.addresses "" ipv4.gateway "" ipv4.dns "" >> "$LOG" 2>&1
    nmcli con mod "$FB_CONN_NAME" ipv6.method auto ipv6.addresses "" ipv6.gateway "" ipv6.dns "" >> "$LOG" 2>&1
    nmcli -w 3 con up "$FB_CONN_NAME" >> "$LOG" 2>&1 || nmcli -w 3 device connect "$FB_IFACE" >> "$LOG" 2>&1
    configure_data_plane
    log "firstboot:network: DHCP apply completed, continuing firstboot"
    show_continue_notice
}

select_manual_network_mode() {
    $DIALOG \
    --clear \
    --visit-items \
    --default-item "1" \
        --backtitle "$BT" \
    --title "Management IP Configuration" \
        --ok-label "Next" \
        --extra-button \
        --extra-label "Back" \
        --nocancel \
        --menu "\nSelect how the management interface receives its IP address.\n" \
        $H1 $W1 8 \
        1 "Static IP Configuration" \
        2 "Automatic IP Configuration (DHCP)" \
        2>"$tempfile"

    [ "$?" = "3" ] && {
        log "firstboot:network: user selected back at mode menu"
        BACK_TO="40-hostname"
        return 1
    }

    MANUAL_NET_MODE="$(cat "$tempfile")"
    [ -n "$MANUAL_NET_MODE" ] || return 2
    return 0
}

select_static_ip_mode() {
    # IPv6-only mode is intentionally suppressed for now.
    # To restore it, remove '#' from the sample option line below and
    # from the commented STATIC_IP_MODE=3 case blocks further down.
    # 3 "Pure IPv6 Configuration" \
    $DIALOG \
        --clear \
        --visit-items \
        --backtitle "$BT" \
        --title "Address Family" \
        --ok-label "Next" \
        --extra-button \
        --extra-label "Back" \
        --nocancel \
        --menu "\nSelect the address family for the management network.\n\nUse dual stack only when IPv6 is available on the network.\n" \
        $H1 $W1 8 \
        1 "IPv4 Only" \
        2 "IPv4 and IPv6 (Dual Stack)" \
        2>"$tempfile"

    [ "$?" = "3" ] && return 1

    STATIC_IP_MODE="$(cat "$tempfile")"
    [ -n "$STATIC_IP_MODE" ] || return 2
    return 0
}

collect_ipv4_details() {
    local ipv4_cidr ipv4_addr ipv4_mask ipv4_gw ipv4_dns1 ipv4_dns2 prefix confirm
    local d_ipv4_cidr d_ipv4_gw d_ipv4_dns1 d_ipv4_dns2

    d_ipv4_cidr="$IPV4_CIDR"
    d_ipv4_gw="${IPV4_GW}"
    d_ipv4_dns1="$(echo "${IPV4_DNS}" | awk '{print $1}')"
    d_ipv4_dns2="$(echo "${IPV4_DNS}" | awk '{print $2}')"

    while true ; do
        $DIALOG \
            --clear \
            --visit-items \
            --backtitle "$BT" \
            --title "Management Network Address" \
            --ok-label "Next" \
            --extra-button \
            --extra-label "Back" \
            --nocancel \
            --form "\nUse the address and subnet together in CIDR format. This network carries management traffic.\n\nExample address: 192.168.10.25/24\nExample gateway: 192.168.10.1\nDNS is optional; leave it blank to use the network defaults.\n\n[Tab: Move between fields | Enter: Continue]\n" \
            $H1 $W1 12 \
            "Management IP / prefix" 1 1 "$d_ipv4_cidr" 1 27 27 39 \
            "Default gateway" 2 1 "$d_ipv4_gw" 2 27 27 39 \
            "Preferred DNS (optional)" 3 1 "$d_ipv4_dns1" 3 27 27 39 \
            "Alternate DNS (optional)" 4 1 "$d_ipv4_dns2" 4 27 27 39 \
            2>"$tempfile"

        [ "$?" = "3" ] && return 1

        ipv4_cidr=$(trim_ws "$(sed -n '1p' "$tempfile")")
        ipv4_gw=$(trim_ws "$(sed -n '2p' "$tempfile")")
        ipv4_dns1=$(trim_ws "$(sed -n '3p' "$tempfile")")
        ipv4_dns2=$(trim_ws "$(sed -n '4p' "$tempfile")")
        d_ipv4_cidr="$ipv4_cidr"
        d_ipv4_gw="$ipv4_gw"
        d_ipv4_dns1="$ipv4_dns1"
        d_ipv4_dns2="$ipv4_dns2"

        ipv4_addr="${ipv4_cidr%%/*}"
        ipv4_mask="${ipv4_cidr#*/}"
        if [ "$ipv4_cidr" = "$ipv4_addr" ] || [ -z "$ipv4_addr" ] || [ -z "$ipv4_mask" ] || [ -z "$ipv4_gw" ] ; then
            $DIALOG --backtitle "$BT" --title "Invalid Network Address" --msgbox "\nEnter the management IPv4 address in CIDR notation and provide a gateway.\n\nExample address: 192.168.10.25/24\nExample gateway: 192.168.10.1\n" $H1 $W1
            continue
        fi

        if ! is_valid_ipv4_addr "$ipv4_addr" ; then
            $DIALOG --backtitle "$BT" --title "Invalid IPv4 Address" --msgbox "\nEnter a valid management IPv4 address.\n\nExample: 192.168.1.10\n" $H1 $W1
            continue
        fi

        if ! is_valid_ipv4_addr "$ipv4_gw" ; then
            $DIALOG --backtitle "$BT" --title "Invalid Default Gateway" --msgbox "\nEnter a valid management IPv4 gateway.\n\nExample: 192.168.1.1\n" $H1 $W1
            continue
        fi

        if [ -n "$ipv4_dns1" ] && ! is_valid_ipv4_addr "$ipv4_dns1" ; then
            $DIALOG --backtitle "$BT" --title "Invalid Preferred DNS Address" --msgbox "\nEnter a valid IPv4 address for the preferred DNS server or leave the field blank.\n\nExample: 8.8.8.8\n" $H1 $W1
            continue
        fi

        if [ -n "$ipv4_dns2" ] && ! is_valid_ipv4_addr "$ipv4_dns2" ; then
            $DIALOG --backtitle "$BT" --title "Invalid Alternate DNS Address" --msgbox "\nEnter a valid IPv4 address for the alternate DNS server or leave the field blank.\n\nExample: 8.8.4.4\n" $H1 $W1
            continue
        fi

        prefix=$(mask_to_prefix "$ipv4_mask") || {
            $DIALOG --backtitle "$BT" --title "Invalid Subnet Prefix" --msgbox "\nThe IPv4 subnet prefix must be between 0 and 32.\n\nExample: /24 represents 255.255.255.0.\n" $H1 $W1
            continue
        }

        confirm="$($DIALOG --clear --backtitle "$BT" --title "Confirm Management Configuration" --yesno "\nReview the management network configuration before applying it.\n\nIPv4 address:  $ipv4_addr/$prefix\nGateway:       $ipv4_gw\nPreferred DNS: ${ipv4_dns1:-Network default}\n\nThis route is reserved for management traffic." $H1 $W1; echo $?)"
        [ "$confirm" = "0" ] || continue
        IPV4_CIDR="$ipv4_addr/$prefix"
        IPV4_GW="$ipv4_gw"
        IPV4_DNS="$ipv4_dns1"
        [ -n "$ipv4_dns2" ] && IPV4_DNS="${IPV4_DNS}${IPV4_DNS:+ }$ipv4_dns2"
        return 0
    done
}

collect_ipv6_details() {
    local ipv6_addr ipv6_gw ipv6_dns
    local d_ipv6_addr d_ipv6_gw d_ipv6_dns

    d_ipv6_addr="${IPV6_ADDR}"
    d_ipv6_gw="${IPV6_GW}"
    d_ipv6_dns="${IPV6_DNS}"

    while true ; do
        $DIALOG \
            --clear \
            --visit-items \
            --backtitle "$BT" \
            --title "Static IPv6 Configuration" \
            --ok-label "Next" \
            --extra-button \
            --extra-label "Back" \
            --nocancel \
            --form "\nEnter IPv6 settings.\nPrefix is optional; if omitted, /64 is used.\n\n[Tab: Switch fields | Enter: Accept | Arrows: Navigate]\n" \
            $H1 $W1 7 \
            "IPv6 Address" 1 1 "$d_ipv6_addr" 1 28 30 64 \
            "Default Gateway" 2 1 "$d_ipv6_gw" 2 28 30 64 \
            "DNS Servers (optional)" 3 1 "$d_ipv6_dns" 3 28 30 64 \
            2>"$tempfile"

        [ "$?" = "3" ] && return 1

        ipv6_addr=$(trim_ws "$(sed -n '1p' "$tempfile")")
        ipv6_gw=$(trim_ws "$(sed -n '2p' "$tempfile")")
        ipv6_dns=$(trim_ws "$(sed -n '3p' "$tempfile")")
        d_ipv6_addr="$ipv6_addr"
        d_ipv6_gw="$ipv6_gw"
        d_ipv6_dns="$ipv6_dns"

        if [ -z "$ipv6_addr" ] || [ -z "$ipv6_gw" ] ; then
            $DIALOG --backtitle "$BT" --title "Incomplete IPv6 Configuration" --msgbox "\nEnter both an IPv6 address and a default gateway.\n" $H1 $W1
            continue
        fi

        echo "$ipv6_addr" | grep -q '/' || ipv6_addr="$ipv6_addr/64"

        if ! is_valid_ipv6_cidr "$ipv6_addr" ; then
            $DIALOG --backtitle "$BT" --title "Invalid IPv6 Address" --msgbox "\nInvalid IPv6 address.
Enter a valid IPv6 address with an optional prefix.
Example: 2001:db8::1 or 2001:db8::1/64\n" $H1 $W1
            continue
        fi

        if ! is_valid_ipv6_addr "$ipv6_gw" ; then
            $DIALOG --backtitle "$BT" --title "Invalid IPv6 Gateway" --msgbox "\nInvalid IPv6 gateway.
Enter a valid IPv6 gateway.
Example: fe80::1\n" $H1 $W1
            continue
        fi

        if ! is_valid_ipv6_dns_list "$ipv6_dns" ; then
            $DIALOG --backtitle "$BT" --title "Invalid IPv6 DNS Configuration" --msgbox "\nInvalid IPv6 DNS list.
Enter one or more IPv6 DNS addresses separated by spaces.
Example: 2001:4860:4860::8888 2001:4860:4860::8844\n" $H1 $W1
            continue
        fi

        IPV6_ADDR="$ipv6_addr"
        IPV6_GW="$ipv6_gw"
        IPV6_DNS="$ipv6_dns"
        return 0
    done
}

apply_manual_network() {
    log "firstboot:network: applying static network config on $FB_CONN_NAME/$FB_IFACE (mode=$STATIC_IP_MODE)"
    ensure_firstboot_connection
    nmcli con mod "$FB_CONN_NAME" connection.interface-name "$FB_IFACE" >> "$LOG" 2>&1

    # Start from clean config then enable only selected protocol(s).
    nmcli con mod "$FB_CONN_NAME" ipv4.method disabled ipv4.addresses "" ipv4.gateway "" ipv4.dns "" >> "$LOG" 2>&1
    nmcli con mod "$FB_CONN_NAME" ipv6.method ignore ipv6.addresses "" ipv6.gateway "" ipv6.dns "" >> "$LOG" 2>&1

    case "$STATIC_IP_MODE" in
        1|2)
            nmcli con mod "$FB_CONN_NAME" ipv4.method manual ipv4.addresses "$IPV4_CIDR" ipv4.gateway "$IPV4_GW" >> "$LOG" 2>&1
            nmcli con mod "$FB_CONN_NAME" ipv4.dns "$IPV4_DNS" >> "$LOG" 2>&1
            ;;
    esac

    case "$STATIC_IP_MODE" in
        2)
            nmcli con mod "$FB_CONN_NAME" ipv6.method manual ipv6.addresses "$IPV6_ADDR" ipv6.gateway "$IPV6_GW" >> "$LOG" 2>&1
            nmcli con mod "$FB_CONN_NAME" ipv6.dns "$IPV6_DNS" >> "$LOG" 2>&1
            ;;
        # 3)
        #     # IPv6-only mode (suppressed). Keep for future re-enable.
        #     nmcli con mod "$FB_CONN_NAME" ipv6.method manual ipv6.addresses "$IPV6_ADDR" ipv6.gateway "$IPV6_GW" >> "$LOG" 2>&1
        #     nmcli con mod "$FB_CONN_NAME" ipv6.dns "$IPV6_DNS" >> "$LOG" 2>&1
        #     ;;
    esac

    nmcli -w 3 con up "$FB_CONN_NAME" >> "$LOG" 2>&1 || nmcli -w 3 device connect "$FB_IFACE" >> "$LOG" 2>&1
    configure_data_plane
    persist_proxy_settings || log "firstboot:network: failed to persist proxy settings"
    log "firstboot:network: manual network apply completed, continuing firstboot"
    show_continue_notice
    return 0
}

setup_manual_network() {
    while true ; do
        select_firstboot_interface
        case "$?" in
            0) break ;;
            1) return 1 ;;
            *) continue ;;
        esac
    done

    select_data_interface || return 1

    configure_proxy
    case "$?" in
        0) ;;
        1) return 1 ;;
        *) continue ;;
    esac

    while true ; do
        select_manual_network_mode
        case "$?" in
            0) ;;
            1) return 1 ;;
            *) continue ;;
        esac

        case "$MANUAL_NET_MODE" in
            1)
                while true ; do
                    select_static_ip_mode
                    case "$?" in
                        0) ;;
                        1) break ;;
                        *) continue ;;
                    esac

                    case "$STATIC_IP_MODE" in
                        1)
                            collect_ipv4_details
                            case "$?" in
                                0) apply_manual_network; return 0 ;;
                                1) continue ;;
                                *) continue ;;
                            esac
                            ;;
                        2)
                            while true ; do
                                collect_ipv4_details
                                case "$?" in
                                    0) ;;
                                    1) break ;;
                                    *) continue ;;
                                esac

                                collect_ipv6_details
                                case "$?" in
                                    0) apply_manual_network; return 0 ;;
                                    1) continue ;;
                                    *) continue ;;
                                esac
                            done
                            ;;
                        # 3)
                        #     # Pure IPv6 mode (suppressed). Remove '#' to re-enable.
                        #     while true ; do
                        #         collect_ipv6_details
                        #         case "$?" in
                        #             0) apply_manual_network; return 0 ;;
                        #             1) continue ;;
                        #             *) continue ;;
                        #         esac
                        #     done
                        #     ;;
                        *)
                            continue
                            ;;
                    esac
                done
                ;;
            2)
                # Enable both IPv4 and IPv6 DHCP/autoconfig; if IPv6 is unavailable,
                # IPv4 DHCP will still bring the interface up.
                setup_dhcp_network
                persist_proxy_settings || log "firstboot:network: failed to persist proxy settings"
                return 0
                ;;
            *)
                continue
                ;;
        esac
    done
}

if [ -n "$AUTOINST" ] ; then
    if discover_network_interfaces ; then
        FB_IFACE="$(get_first_discovered_interface)"
        SELECTED_NIC="$FB_IFACE"
        set_connection_profile_name
        [ -n "$SELECTED_NIC" ] && bring_interfaces_to_selected_state "$SELECTED_NIC"
        [ -n "$FB_IFACE" ] && log "firstboot:network:auto-selected interface=$FB_IFACE profile=$FB_CONN_NAME"
    fi
    [ -n "$FB_IFACE" ] || FB_IFACE="eth0"
    setup_dhcp_network
else
    while true ; do
        setup_manual_network || return 1
        configure_ntp_server
        case "$?" in
            0) break ;;
            2) continue ;;
            *) return 1 ;;
        esac
    done
fi
