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

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

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

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

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

EXITSTATUS=0
ip link set "$IFACE" up
do_sleep 0.5
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"

