#!/bin/bash
# -*-mode: sh; tab-width: 8; coding: utf-8-unix -*-

ROLE=proxy
prog=$( basename $0 .bash )
. /usr/local/bin/usr_local_tput.bash
PREFIX=/usr/local

[ $( id -u ) -eq 0 ] || { ERROR "this must be run as root" ; exit 1 ; }

LOG=/tmp/I$$.log
JSON=/tmp/I$$.json

. /usr/local/bin/proxy_ping_lib.bash || \
    { echo ERROR: loading /usr/local/bin/proxy_ping_lib.bash ; exit 3; }
. /usr/local/bin/usr_local_base.bash || exit 2

PROXY_WLAN=$(route |grep ^def |sed -e 's/.* //') || { echo ERROR: " no route $?" ; exit 4 ; }
if [ -z "$PROXY_WLAN" ] ; then
PROXY_WLAN=$( proxy_get_if )
[ $? -eq 0 ] || { echo ERROR: " error getting device $?" ; exit 5 ; }
fi

[ -d /etc/NetworkManager/system-connections ] || exit 0
cd /etc/NetworkManager/system-connections/ || exit 6

pgrep NetworkManager >/dev/null || \
  /etc/init.d/network-manager start # || exit 7

iwlist $PROXY_WLAN scan > $LOG 2>&1 || { echo ERROR: failed iwlist scan ; exit 2 ; }

which yq 2>/dev/null >/dev/null && \
for file in *.nmconnection; do
    elt=$( basename "$file" .nmconnection )
    grep -q "$elt" "$LOG" || continue
    L=$( cat $LOG | grep -B 5 "$elt" | sed -e 's@/.*@@' -e 's@[=:]@: @' -e 's/.*Addre/- Addre/' -e '/^--\|Frequency:\|Encryption/d' -e 's/^   */  /' | yq 'sort_by(.Quality)|reverse|map(del(.Channel))|.[0:4]'|grep Address|sed -e 's/,/;/' -e 's/ *.Address.: //'|xargs echo|sed -e 's/ //g' )
    [ -z "$L" ] && continue
    sed -e "s@^seen-bssids=.*@seen-bssids=$L@" -i "$file"

    grep -q lldp=0 "$file"  || echo WARN:   nmcli con modify $elt connection.lldp 0
    grep -q llmnr=0 "$file" || echo WARN:   nmcli con modify $elt connection.llmnr 0
    grep -q mdns=0 "$file"  || echo WARN:   nmcli con modify $elt connection.mdns 0

    INFO $prog $PWD/$file

  done
rm -f /tmp/I$$.log

[ "$#" -eq 0 ] && exit 0
[ $1 = connect ] && nmtui-connect
[ $1 = edit ] && nmtui-edit
