aboutsummaryrefslogtreecommitdiff
path: root/.local/bin/bcn
blob: 340f6c0c33a9eb3463e74b4f927fdae92bb480ec (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
#!/bin/bash

# bcn, Bluetooth Connect

mapfile -t devices < <(bluetoothctl devices)

if [[ ${#devices[@]} -eq 0 ]]; then
    notify-send "Bluetooth" "No devices found"
    exit 1
fi

if [[ ${#devices[@]} -eq 1 ]]; then
    line="${devices[0]}"
else
    names=$(printf '%s\n' "${devices[@]}" | sed 's/^Device [^ ]* //')

    selected=$(printf '%s\n' "$names" |
        fuzzel --dmenu -l 10 -fn Monospace-15)

    [[ -z "$selected" ]] && exit 0

    # Find MAC corresponding to selected full name
    for device in "${devices[@]}"; do
        name=$(echo "$device" | cut -d' ' -f3-)

        if [[ "$name" == "$selected" ]]; then
            line="$device"
            break
        fi
    done
fi

MAC=$(echo "$line" | awk '{print $2}')
NAME=$(echo "$line" | cut -d' ' -f3-)

connect=$(bluetoothctl info "$MAC" |
    awk '/Connected:/ {print $2}')

if [[ "$connect" == "no" ]]; then
    notify-send "Bluetooth" "Connecting to $NAME..."

    if bluetoothctl connect "$MAC"; then
        notify-send "Bluetooth" "Connected to $NAME"
    else
        notify-send "Bluetooth" "Failed to connect to $NAME"
    fi

elif [[ "$connect" == "yes" ]]; then
    notify-send "Bluetooth" "Disconnecting from $NAME..."
    bluetoothctl disconnect "$MAC"
fi