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

FB_CONN_NAME="slos"
FB_IFACE="$(nmcli -t -f DEVICE,TYPE device status 2>/dev/null | awk -F: '$2 == "ethernet" { print $1; exit }')"
[ -z "$FB_IFACE" ] && FB_IFACE="eth0"

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 }
        {
            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--) {
                    if (and(v, lshift(1,b))) c++
                }
            }
            print c+0
        }')

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

ensure_firstboot_connection() {
    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
}

show_continue_notice() {
    $DIALOG --backtitle "$BT" --title "Firstboot" --infobox "\n Network saved. Continuing firstboot..." $H1 $W1
    sleep 1
    # Avoid dependence on external clear command.
    printf '\033[2J\033[H'
}

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\nHint: Use Up/Down arrows to select mode. Press Tab to move to Next/Back.\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\nHint: Use Up/Down arrows to select mode. Press Tab to move to Next/Back.\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 "\nHint: Use Up/Down arrows in fields. Press Tab to move to Next/Back.\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=$(sed -n '1p' "$tempfile")
        ipv4_mask=$(sed -n '2p' "$tempfile")
        ipv4_gw=$(sed -n '3p' "$tempfile")
        ipv4_dns1=$(sed -n '4p' "$tempfile")
        ipv4_dns2=$(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

        prefix=$(mask_to_prefix "$ipv4_mask") || {
            $DIALOG --backtitle "$BT" --title "Error" --msgbox "\nInvalid mask/prefix. Use dotted mask (255.255.255.0) or CIDR (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\nHint: Use Up/Down arrows in fields. Press Tab to move to Next/Back.\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=$(sed -n '1p' "$tempfile")
        ipv6_gw=$(sed -n '2p' "$tempfile")
        ipv6_dns=$(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"
        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_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
    setup_dhcp_network
else
    setup_manual_network || return 1
fi
