#!/bin/bash
#
# test-wifi-id
#
# Usage:
#   test-wifi-id IFACE [ESSID] [MACADDRESS]
#
# MACADDRESS letters must be in upper case
#
# This tests whether the current interface has [the approprate
# ESSID] [and appropriate MAC address]
#
# Licensed under the GNU GPL.  See /usr/share/common-licenses/GPL.
#
# History
# Dec 2003: Written by Thomas Hood

set -o errexit   # -e
set -o noglob    # -f

MYNAME="$(basename $0)"
PATH=/sbin:/bin

report_err() { echo "${MYNAME}: Error: $*" >&2 ; }

is_ethernet_mac()
{
	[ "$1" ] && [ ! "${1/[0-9A-F][0-9A-F]:[0-9A-F][0-9A-F]:[0-9A-F][0-9A-F]:[0-9A-F][0-9A-F]:[0-9A-F][0-9A-F]:[0-9A-F][0-9A-F]/}" ]
}

IFACE="$1"
[ "$IFACE" ] || { report_err "Interface not specified.  Exiting." ; exit 1 ; }
shift
for arg in "$@" ; do
	if is_ethernet_mac "$arg" ; then
		MAC_ADDRESS="$arg"
	else
		ESSID="$arg"
	fi
done
[ "$MAC_ADDRESS" ] || [ "$ESSID" ] || { report_err "Neither AP MAC address nor ESSID specified.  Exiting." ; exit 1 ; }

EXITSTATUS=0
ip link set "$IFACE" up
if [ "$MAC_ADDRESS" ] ; then
	ACTUAL_MAC_ADDRESS="$(iwgetid "$IFACE" --ap)"
	ACTUAL_MAC_ADDRESS="${ACTUAL_MAC_ADDRESS#*Cell:}"
	ACTUAL_MAC_ADDRESS="${ACTUAL_MAC_ADDRESS# }"
	ACTUAL_MAC_ADDRESS="${ACTUAL_MAC_ADDRESS% }"
	[ "$ACTUAL_MAC_ADDRESS" = "$MAC_ADDRESS" ] || EXITSTATUS=1
fi
if [ "$ESSID" ] ; then
	ACTUAL_ESSID="$(iwgetid "$IFACE")"
	ACTUAL_ESSID="${ACTUAL_ESSID#*ESSID:\"}"
	ACTUAL_ESSID="${ACTUAL_ESSID%\"*}"
	[ "$ACTUAL_ESSID" = "$ESSID" ] || EXITSTATUS=1
fi
ip link set "$IFACE" down
exit "$EXITSTATUS"

