#!/bin/sh

: <<=cut

=head1 NAME

brc_rssi - monitor RSSI (Received Signal Strength Indication) of wireless accesspoints

=head1 APPLICABLE SYSTEMS

Wireless accesspoints with Broadcom chipset such as found on hardware supported by OpenWRT.
The utility "wl" is required.


=head1 CONFIGURATION

 [brc_rssi]
 env.WIFISIDE eth0   # Set the WiFi side interface. Used to filter arp entries.
                     # On a openwrt box defaults to "nvram get lan_ifname" otherwise
                     # no default.


=head1 BUGS

=over 4

=item Should have a persistent list of macs ever seen.

=back


=head1 AUTHORS

Copyright (C) 2007 Nicolai Langfeldt <janl@linpro.no>


=head1 LICENSE

GNU General Public License v2.0 only

SPDX-License-Identifier: GPL-2.0-only


=head1 MAGIC MARKERS

 #%# family=contrib
 #%# capabilities=autoconf

=cut


PATH=/usr/bin:/usr/sbin:/bin:/sbin
export PATH

AL="$(wl assoclist 2>&1)"
WLERR=$?
case $WLERR in
    0) MACS="$(echo "$AL" | cut -d' ' -f2)";;
esac

do_ () {
    # Fetch
    for M in $MACS; do
	RSSI=$(wl rssi $M | cut -d' ' -f3)
        m=$(echo $M | tr -d ':')
	echo rssi$m.value $RSSI
    done
}

do_config () {
    cat <<'EOF'
graph_title WiFi AP RSSI
graph_vlabel dB(?)
graph_category network
graph_info This plugin shows the RSSI (Received Signal Strength Indication) as reported by the Access Point (AP) driver. The plugin is specific to broadcom wireless chipsets such as used on WRT hardware. We're not <em>quite</em> sure about the units the RSSI is measured in as this is not documented. Both dB and dBm are apparently candidates.  Higher is better.
EOF
    # Attempt to find default. "Set default" and "assign default" syntax is
    # not available in busybox (which is used in openwrt firmware) it seems.
    # So work around it with case.
    : ${WIFISIDE:=$(nvram get lan_ifname 2>/dev/null)}
    : ${WIFISIDE:=$(awk '/:/ { gsub(/^ */,""); gsub(/:/," "); print $1; exit 0; }' /proc/net/wireless)}

    HOSTS="$(cat /etc/hosts)"
    ETHERS="$( ( cat /etc/etherss 2>/dev/null; awk '/'$WIFISIDE'$/ { print $4" "$1 }' /proc/net/arp ) | sort -u)"
    for M in $MACS; do
	m=$(echo $M | tr -d ':')
	LABEL=$M
        NAME=''

        IP=$(echo "$ETHERS" | awk '/^'$M'/ { print $2; }')
	case $IP in
		'') :;;
		*)  LABEL=$IP
		    # Make IP "RE safe"
		    IP="$(echo $IP | sed 's/\./\\./g')"
		    NAME=$(echo "$HOSTS" | awk '/^'$IP'/ { print $2; }')
	esac
	case $NAME in
		'') :;;
		*)  LABEL=$NAME;;
	esac
	echo rssi$m.label $LABEL
    done
}

do_autoconf () {
    case $WLERR in
        0) echo yes;;
        127) echo "no ($AL)";;
        *) echo "no (wl error: $AL)";;
    esac
    exit 0
}

case $1 in
     ''|config|autoconf)
	eval do_$1;;
esac
