summaryrefslogtreecommitdiff
path: root/scripts/dmenu-iwd
blob: a3cc4113601907c06092992f4e0a893a5793a823 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/bin/bash

STATION="wlan0"
FONT="Monospace"
NORMAL_BACKGROUND="#000000"
NORMAL_FOREGROUND="#8f8f8f"
SELECTED_BACKGROUND="#000000"
SELECTED_FOREGROUND="#00ff00"
FLAGS=(
    "-i"
    "-nb" "$NORMAL_BACKGROUND"
    "-nf" "$NORMAL_FOREGROUND"
    "-sb" "$SELECTED_BACKGROUND"
    "-sf" "$SELECTED_FOREGROUND"
    "-fn" "$FONT"
)

remove_colors() {
    sed -E 's/\x1B\[[0-9;]*[JKmsu]//g'
}

connect() {
    SSID="$1"
    notify-send --urgency=low "Attempting to connect to network: $SSID"
    if iwctl station "$STATION" connect "$SSID" --dont-ask; then
        notify-send "Connected to network: $SSID"
        exit 0
    fi
    if ERROR=$(
        iwctl station "$STATION" connect "$SSID" \
            --passphrase "$(dmenu "${FLAGS[@]}" -p Password: </dev/null)" \
            --dont-ask 2>&1
    ); then
        notify-send "Connected to network: $SSID"
    else
        notify-send --urgency=critical \
            "Failed to connect to network: $SSID" "$(remove_colors <<<$ERROR)"
    fi
}

networks() {
    iwctl station "$STATION" get-networks | awk '
BEGIN {
    i = -1
}
{
    i++
    if (i < 4) next # skip header

    network = ""
    strength = 0
    for (ix = 1; ix <= NF; ix++) {
        if (ix == NF - 1) continue # skip protocol

        # calculate strength by reading *s until
        # a color code is encountered
        char = sprintf("%c", $ix)
        if (char == "*") {
            split($ix, chars, "")
            for (c = 1; c <= length($ix); c++) {
                char = sprintf("%c", chars[c])
                if (char == "\033") break
                strength++
            }
            continue
        }

        if (char == "\033") continue # color codes
        if ($ix == "") continue # whitespace
        if ($ix == ">") continue # current network

        # ssids may contain spaces
        if (network == "") {
            network = $ix
            continue
        }
        network = network " " $ix
    }
    if (network == "") next
    networks[network] = strength
}
END {
    for (s = 4; s >= 0; s--) {
        for (network in networks) {
            if (networks[network] == s) {
                print network
                delete networks[network]
            }
        }
    }
}
'
}

SELECTION=$(networks | dmenu "${FLAGS[@]}") || exit 1
connect "$SELECTION"