#!/bin/bash
#
# test-wifi-scan
#
# Usage:
#   test-wifi-scan IFACE [ESSID] [MACADDRESS]
#
# MACADDRESS letters must be in upper case
#
# This tests whether an access point is in range [with the appropriate
# ESSID] [and appropriate MAC address] by looking at the output of
# "iwlist IFACE scan".
#
# Unfortunately, this method fails to work with those cards whose
# drivers do not support AP scanning.
#
# Licensed under the GNU GPL.  See /usr/share/common-licenses/GPL.
#
# History
# Nov 2003: Modified by Thomas Hood and Klaus Wacker
# Jan,July 2003: Written by Thomas Hood <jdthood@yahoo.co.uk>

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 ; }

ip link set "$IFACE" up
scan="$(iwlist "$IFACE" scan 2>&1)"
ip link set "$IFACE" down

shopt -s extglob  # We need this to allow the ?( ) syntax in patterns
[ "$scan" = "${scan/Interface doesn?t support scanning/}" ] || exit 1
[ "$scan" = "${scan/Operation not supported/}" ] || exit 1
if [ "$MAC_ADDRESS" ] ; then
	[ "$scan" != "${scan/Address:*( )$MAC_ADDRESS/}" ] || exit 1
fi
if [ "$ESSID" ] ; then
	[ "$scan" != "${scan/ESSID:*( )?${ESSID}?/}" ] || exit 1
fi
exit 0

