# 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=""

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

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 nic_module
    local kernel_rel
    local selinux_mode=""
    local module_roots
    local nic_modules=(e1000e igb tg3 r8169 ixgbe i40e ice bnx2 vmxnet3 virtio_net)
    NIC_DISCOVERY_FILE="/tmp/firstboot.nic.discovery.$$"
    : > "$NIC_DISCOVERY_FILE"
    kernel_rel="$(uname -r 2>/dev/null)"
    module_roots="/usr/lib/modules /usr/lib/modules/$kernel_rel /lib/modules /lib/modules/$kernel_rel"

    # Detect SELinux mode when available; empty means SELinux tools are absent.
    if command -v getenforce >/dev/null 2>&1 ; then
        selinux_mode="$(getenforce 2>/dev/null)"
    fi

    # 1. Trigger the parent PCI bus to match vendor/device IDs and load modules
    udevadm trigger --subsystem-match=pci --action=add >/dev/null 2>&1

    # 2. Trigger network subsystem updates for newly discovered devices
    udevadm trigger --subsystem-match=net --action=add >/dev/null 2>&1

    # 3. Settle all pending uevents
    udevadm settle --timeout=15 >/dev/null 2>&1

    # SELinux guard: when enforcing/permissive, ensure module trees are labeled.
    # This avoids AVC module_load denials from unlabeled module paths.
    if [ "$selinux_mode" = "Enforcing" ] || [ "$selinux_mode" = "Permissive" ] ; then
        if command -v restorecon >/dev/null 2>&1 ; then
            for root in $module_roots ; do
                [ -d "$root" ] && restorecon -RF "$root" >/dev/null 2>&1
            done
        fi
    fi

    # Fallback guard: proactively probe common NIC drivers in minimal environments.
    for nic_module in "${nic_modules[@]}" ; do
        modprobe "$nic_module" 2>/dev/null
    done

    # Retry probing after relabel attempt for SELinux-blocked cold-boot paths.
    if [ "$selinux_mode" = "Enforcing" ] || [ "$selinux_mode" = "Permissive" ] ; then
        for nic_module in "${nic_modules[@]}" ; do
            modprobe "$nic_module" 2>/dev/null
        done
    fi
    sleep 3

    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

    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
    NIC_MENU_FILE="/tmp/firstboot.nic.menu.$$"

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

        if command -v getenforce >/dev/null 2>&1 ; then
            diag_selinux="$(getenforce 2>/dev/null)"
        fi
        [ -r /proc/sys/kernel/modules_disabled ] && diag_modules_disabled="$(cat /proc/sys/kernel/modules_disabled 2>/dev/null)"

        {
            echo "=== Network Diagnostics ==="
            echo
            echo "SELinux mode: ${diag_selinux:-Unavailable}"
            echo "kernel.modules_disabled: ${diag_modules_disabled:-Unknown}"
            echo
            if [ "$diag_selinux" = "Enforcing" ] || [ "$diag_selinux" = "Permissive" ] ; then
                if dmesg | grep -qiE 'avc:.*denied.*module_load' ; then
                    echo "POSSIBLE ROOT CAUSE: SELinux is denying module_load."
                    echo "Check module labels (often unlabeled_t) and run restorecon on module paths."
                    echo
                fi
            fi
            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, please wait...\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
            continue
        fi

        : > "$NIC_MENU_FILE"
        while IFS='|' read -r iface driver mac speed ; do
            printf '"%s" "%s"\n' "$iface" "$(format_nic_menu_desc "$driver" "$mac" "$speed")" >> "$NIC_MENU_FILE"
        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 Network Interface" \
            --ok-label "Next" \
            --extra-button \
            --extra-label "Back" \
            --nocancel \
            --default-item "$default_iface" \
            --menu "\nChoose the interface to configure.\n\n[Tab: Switch fields | Enter: Accept | Arrows: Navigate]\n" \
            $H1 $W1 12 \
            --file "$NIC_MENU_FILE" \
            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
}

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
}

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

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.\n\nThis is mandatory for proper node synchronization with SSE.\nPlease make sure your NTP server is up and active, or use the default one.\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 "\nPlease enter a valid NTP server address or IP address.\nExample: pool.ntp.org or 192.168.1.1\n" $H1 $W1
            continue
        fi

        ntp_tmp="${chrony_conf}.firstboot.$$"
        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" && cat "$ntp_tmp" > "$chrony_conf"
        else
            printf 'server %s\n' "$ntp_server" > "$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
    log "firstboot:network: DHCP apply completed, continuing firstboot"
    show_continue_notice
}

select_manual_network_mode() {
    $DIALOG \
        --clear \
        --visit-items \
        --default-item "2" \
        --backtitle "$BT" \
        --title "Network Setup Mode" \
        --ok-label "Next" \
        --extra-button \
        --extra-label "Back" \
        --nocancel \
        --menu "\nChoose network setup mode.\n\n[Tab: Switch fields | Enter: Accept | Arrows: Navigate]\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 "Static IP Mode" \
        --ok-label "Next" \
        --extra-button \
        --extra-label "Back" \
        --nocancel \
        --menu "\nChoose static IP assignment type.\n\n[Tab: Switch fields | Enter: Accept | Arrows: Navigate]\n" \
        $H1 $W1 8 \
        1 "Pure IPv4 Configuration" \
        2 "Dual Stack (IPv4 + IPv6)" \
        2>"$tempfile"

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

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

collect_ipv4_details() {
    local ipv4_addr ipv4_mask ipv4_gw ipv4_dns1 ipv4_dns2 prefix
    local d_ipv4_addr d_ipv4_mask d_ipv4_gw d_ipv4_dns1 d_ipv4_dns2

    d_ipv4_addr="${IPV4_CIDR%%/*}"
    d_ipv4_mask=""
    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 "NETWORK CONFIGURATION" \
            --ok-label "Next" \
            --extra-button \
            --extra-label "Back" \
            --nocancel \
            --form "\n[Tab: Switch fields | Enter: Accept | Arrows: Navigate]\n" \
            $H1 $W1 10 \
            "IPv4 Address" 1 1 "$d_ipv4_addr" 1 24 24 39 \
            "Subnet Mask" 2 1 "$d_ipv4_mask" 2 24 24 39 \
            "Default Gateway" 3 1 "$d_ipv4_gw" 3 24 24 39 \
            "Preferred DNS" 4 1 "$d_ipv4_dns1" 4 24 24 39 \
            "Alternate DNS" 5 1 "$d_ipv4_dns2" 5 24 24 39 \
            2>"$tempfile"

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

        ipv4_addr=$(trim_ws "$(sed -n '1p' "$tempfile")")
        ipv4_mask=$(trim_ws "$(sed -n '2p' "$tempfile")")
        ipv4_gw=$(trim_ws "$(sed -n '3p' "$tempfile")")
        ipv4_dns1=$(trim_ws "$(sed -n '4p' "$tempfile")")
        ipv4_dns2=$(trim_ws "$(sed -n '5p' "$tempfile")")
        d_ipv4_addr="$ipv4_addr"
        d_ipv4_mask="$ipv4_mask"
        d_ipv4_gw="$ipv4_gw"
        d_ipv4_dns1="$ipv4_dns1"
        d_ipv4_dns2="$ipv4_dns2"

        if [ -z "$ipv4_addr" ] || [ -z "$ipv4_mask" ] || [ -z "$ipv4_gw" ] ; then
            $DIALOG --backtitle "$BT" --title "Error" --msgbox "\nIPv4 address, mask/prefix, and gateway are required.\n" $H1 $W1
            continue
        fi

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

        if ! is_valid_ipv4_addr "$ipv4_gw" ; then
            $DIALOG --backtitle "$BT" --title "Error" --msgbox "\nPlease enter a valid IPv4 gateway.\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 "Error" --msgbox "\nPlease enter a valid preferred DNS IPv4 address.\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 "Error" --msgbox "\nPlease enter a valid alternate DNS IPv4 address.\nExample: 8.8.4.4\n" $H1 $W1
            continue
        fi

        prefix=$(mask_to_prefix "$ipv4_mask") || {
            $DIALOG --backtitle "$BT" --title "Error" --msgbox "\nPlease enter a valid network mask or prefix.\nExample: 255.255.255.0 or 24\n" $H1 $W1
            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 "Error" --msgbox "\nIPv6 address and gateway are required.\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 "Error" --msgbox "\nInvalid IPv6 address.
Please 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 "Error" --msgbox "\nInvalid IPv6 gateway.
Please 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 "Error" --msgbox "\nInvalid DNS list.
Please 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
    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

    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
                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
