#!/bin/bash -e

RESCAN=0

NMCLI=(nmcli dev wifi)
CON=("${NMCLI[@]}" connect)

function connect() {
    if ! "${CON[@]}" "$1" 2> /dev/null; then
        if [ "$RESCAN" = 1 ]; then
            return
        fi
        RESCAN=1
        "${NMCLI[@]}" list --rescan yes > /dev/null
        if ! "${CON[@]}" "$1"; then
            return
        fi
    fi

    kill -36 "$(cat "$HOME/.cache/pidofbar")"
    exit
}


if [ -n "$1" ]; then
    connect "$1"
else
    readarray -t NET <<<                                              \
        "$(nmcli -f SSID,CHAN,RATE,SIGNAL,BARS,SECURITY dev wifi list \
        | awk '!seen[$1]++')"
    COLUMNS=1
    select net in "${NET[@]}"; do
        connect "$(awk '{print $1}' <<< "$net")" && break
    done
fi
