#!/bin/bash
#
# test-wireless-scan
#
# History
# Oct 2004: Written by Thomas Hood

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

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

usage() {
cat <<EOT
Usage: $MYNAME <IFACE> [mac <MACADDRESS>] [essid <ESSID>]
       $MYNAME --help|-h

Tests whether an access point is in range [with the appropriate
MAC address] [and appropriate ESSID] by looking at the output of
"iwlist IFACE scan".

MACADDRESS letters must be in upper case

Licensed under the GNU GPL.  See /usr/share/common-licenses/GPL.

Options:
	--help|-h     Print this help
EOT
}

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

do_sleep() { LANG=C sleep "$@" ; }

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]/}" ]
}

if [ "$1" = "--help" ] || [ "$1" == "-h" ]; then
    usage
    exit 0
fi

IFACE="$1"
[ "$IFACE" ] || { report_err "Interface not specified.  Exiting." ; exit 1 ; }
shift
while [ "$2" ] ; do
	case "$1" in
		mac)
			is_ethernet_mac "$2" || { report_err "Argument of 'mac' is not a MAC address" ; exit 1 ; }
			MAC_ADDRESS="$2"
			;;
		essid)
			ESSID="$2"
			;;
	esac
	shift 2
done

[ "$MAC_ADDRESS" ] || [ "$ESSID" ] || { report_err "Neither AP MAC address nor ESSID specified.  Exiting." ; exit 1 ; }

ifconfig "$IFACE" up
do_sleep 0.5
SCAN="$(iwlist "$IFACE" scan 2>&1)"
ifconfig "$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

