#!/bin/bash
: 2>/dev/null > /dev/tcp/ya.ru/80   && exit 0
export TEXTDOMAINDIR=/usr/share/locale
export TEXTDOMAIN=rosa-rw_functions
MSG01="$(gettext -s "No wifi hotspots found,\nsearch again")"
MSG02="$(gettext -s "WIFI network connection")"
MSG03="$(gettext -s "Please, select a hotspot from the list")"
MSG04="$(gettext -s "Password")"

get_nmcli() {
    nmcli  -c no -f SSID device wifi list --rescan yes | tail -n +2 |while read essid ; do
    echo -n "${essid}|"
    done
}

get_essid() {
TLIST=''
while [ -z "$TLIST" ] ; do
    TLIST=$(get_nmcli|sed 's/|$//' )
    if [ -z "$TLIST" ] ; then
    xuserrun zenity --question --text="${MSG01}?" || exit
    fi
done
ESSID_PASS=$(xuserrun zenity --forms --title="$MSG02" \
    --text="${MSG03}:" \
    --separator="" \
    --add-list="ESSID:" \
    --list-values="$TLIST" \
    --add-password="${MSG04}:" \
    --width=400 \
    --name="zenWifi" \
    --class="Xdialog" \
)

ESSID=$(echo "$ESSID_PASS" |cut -f1 -d ",") 
[ -z "$ESSID" ] && exit
PASS=$(echo "$ESSID_PASS" |cut -f2 -d ",")
[ -z "$PASS" ] && exit
}

# Попытка поднять wifi из уже настроенных
n=1
while [ -z $known_wifi ] ; do
    unset known_wifi
    known_wifi=$((nmcli -f name con sh |sort |uniq && nmcli -f ssid dev wifi list --rescan yes |sort |uniq) \
    | sort |sed 's/[[:space:]]*$//g' |uniq -d)
    : 2>/dev/null > /dev/tcp/ya.ru/80   && exit 0
    n=$(( n + 1))
    [ $n -gt 3 ] && break
done

if [ ! -z $known_wifi ] ; then 
    nmcli -f name con sh |tac |grep "$known_wifi" |while read a ; do
	echo \"$a\" 
	nmcli con up "$a" && break
    done
fi

until true 2>/dev/null > /dev/tcp/ya.ru/80 ; do
get_essid
nmcli device wifi connect "$ESSID" password "$PASS"
unset PASS
unset ESSID
sleep 1
done

