# 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 }
        {
            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
}

is_valid_ipv4_addr() {
    local ip="$1"
    echo "$ip" | grep -Eq '^(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}$'
}

trim_ws() {
    echo "$1" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//'
}

is_valid_ipv6_addr() {
    local ip="$1"

    echo "$ip" | awk '
        function parse_side(side, out,   n, i, v) {
            if (side == "") return 0
            n = split(side, t, ":")
            for (i = 1; i <= n; i++) {
                if (t[i] == "") return -1
                # RFC 5952 canonical text: lowercase hex, no leading zeros.
                if (t[i] !~ /^[0-9a-f]{1,4}$/) return -1
                if (length(t[i]) > 1 && substr(t[i], 1, 1) == "0") return -1
                out[i] = t[i]
            }
            return n
        }

        function endswith_colon(x) {
            return substr(x, length(x), 1) == ":"
        }

        {
            s=$0
            if (s == "") exit 1
            if (s !~ /^[0-9a-f:]+$/) exit 1
            if (s ~ /^:[^:]/ || s ~ /[^:]:$/) exit 1

            # Allow at most one "::" compression token.
            dc=0
            for (i=1; i<length(s); i++) {
                if (substr(s,i,2) == "::") dc++
            }
            if (dc > 1) exit 1

            dpos = index(s, "::")
            if (dpos > 0) {
                left = substr(s, 1, dpos-1)
                right = substr(s, dpos+2)

                lcount = parse_side(left, la)
                if (lcount < 0) exit 1
                rcount = parse_side(right, ra)
                if (rcount < 0) exit 1

                omit = 8 - lcount - rcount
                # RFC 5952: do not use "::" to shorten a single 0 field.
                if (omit < 2) exit 1

                idx = 1
                for (i=1; i<=lcount; i++) full[idx++] = la[i]
                for (i=1; i<=omit; i++) full[idx++] = "0"
                for (i=1; i<=rcount; i++) full[idx++] = ra[i]
                if (idx != 9) exit 1
            } else {
                n = parse_side(s, full)
                if (n != 8) exit 1
            }

            # Determine longest (leftmost on ties) run of zero groups.
            best_start = 0
            best_len = 0
            run_start = 0
            run_len = 0
            for (i=1; i<=8; i++) {
                if (full[i] == "0") {
                    if (run_len == 0) run_start = i
                    run_len++
                } else {
                    if (run_len >= 2 && run_len > best_len) {
                        best_len = run_len
                        best_start = run_start
                    }
                    run_len = 0
                }
            }
            if (run_len >= 2 && run_len > best_len) {
                best_len = run_len
                best_start = run_start
            }

            # Rebuild canonical RFC 5952 text and compare with input.
            out = ""
            i = 1
            while (i <= 8) {
                if (best_len >= 2 && i == best_start) {
                    if (out == "") out = "::"
                    else out = out "::"
                    i += best_len
                    if (i > 8) break
                    continue
                }
                if (out != "" && !endswith_colon(out)) out = out ":"
                out = out full[i]
                i++
            }

            if (out != s) exit 1
            exit 0
        }'
}

is_valid_ipv6_cidr() {
    local cidr="$1"
    local ip="${cidr%%/*}"
    local prefix="${cidr##*/}"

    [ -n "$ip" ] || return 1
    [ -n "$prefix" ] || return 1
    echo "$prefix" | grep -Eq '^[0-9]+$' || return 1
    [ "$prefix" -ge 0 ] && [ "$prefix" -le 128 ] || return 1
    is_valid_ipv6_addr "$ip"
}

is_valid_ipv6_dns_list() {
    local dns_list="$1"
    local dns

    [ -z "$dns_list" ] && return 0
    for dns in $dns_list ; do
        is_valid_ipv6_addr "$dns" || return 1
    done
    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=$(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 "\nInvalid IPv4 address format.\n" $H1 $W1
            continue
        fi

        if ! is_valid_ipv4_addr "$ipv4_gw" ; then
            $DIALOG --backtitle "$BT" --title "Error" --msgbox "\nInvalid IPv4 gateway format.\n" $H1 $W1
            continue
        fi

        if [ -n "$ipv4_dns1" ] && ! is_valid_ipv4_addr "$ipv4_dns1" ; then
            $DIALOG --backtitle "$BT" --title "Error" --msgbox "\nInvalid preferred DNS IPv4 address.\n" $H1 $W1
            continue
        fi

        if [ -n "$ipv4_dns2" ] && ! is_valid_ipv4_addr "$ipv4_dns2" ; then
            $DIALOG --backtitle "$BT" --title "Error" --msgbox "\nInvalid alternate DNS IPv4 address.\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=$(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.
Use lowercase hex (0-9, a-f) and colons, with optional prefix /0-128.
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.
Enter a lowercase IPv6 address.
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.
Enter space-separated lowercase IPv6 addresses.
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_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
