#!/usr/bin/env bash
# airmon -- create and destroy Wi-Fi "monitor mode" interfaces
#
# Simpler version of the 'airmon-ng' tool part of aircrack-ng.

. lib.bash || exit

usage() {
	echo "Usage: $progname start|stop"
}

shopt -s nullglob

case $1 in
	start)
		phys=()
		for _phy in /sys/class/ieee80211/phy*; do
			phys+=($_phy)
			phy=${_phy##*/}
			dev=${phy/#phy/mon}
			_dev=/sys/class/net/$dev
			if [[ -e $_dev ]]; then
				echo "'$dev' alreacy exists, skipping $phy"
				continue
			fi
			sudo: iw $phy interface add $dev type monitor
			sudo: ip link set $dev up
		done
		if [[ ! $phys ]]; then
			err "no ieee80211 PHYs found"
		fi
		;;
	stop)
		for _dev in /sys/class/net/*mon*; do
			dev=${_dev##*/}
			type=$(< $_dev/type)
			if [[ $type != 803 ]]; then
				debug "'$dev' is not a monitor interface, skipping"
				continue
			fi
			sudo: iw $dev interface del
		done
		;;
	list)
		echo "phys:"
		for _phy in /sys/class/ieee80211/phy*; do
			phy=${_phy##*/}
			echo "  $phy"
		done
		echo "interfaces:"
		for _dev in /sys/class/net/*; do
			dev=${_dev##*/}
			type=$(< $_dev/type)
			if [[ $type != @(1|803) ]]; then
				continue
			fi
			echo "  $dev ($type)"
		done
		;;
	"")
		usage; die -2 "missing command";;
	*)
		die "unknown command '$1'";;
esac

(( !errors ))
