#!/bin/bash

usage="
        Usage: $(basename "$0") <array_id> [desired-monId] [-h]
      Example: $(basename "$0") wlan0   #<--- add a monitor interface for wlan0, named <phy-name-of-wlan0>mon
      Example: $(basename "$0") wlan0 wlan0Mon1  #<--- add a monitor interface for wlan0, named wlan0Mon1
Functionality: This script adds a monitor interface for the given deviceId/PhyId using the stock iw command.
               If [desired-monId] appears, the added monitor interface is named [desired-monId]; 
               If [desired-monId] is none, the script resolves <array_id> using ANY2PHY command and names the monitor interface as <phyId-of-arrayId>mon.

      Options:
	-h		Show usage information
"

#if [[ $UID == 0 ]]; then
#	(>&2 echo "DO NOT run with sudo.")
#	echo "$usage"
#	exit 1
#fi

while getopts 'h' OPT; do
    case $OPT in
        h)
            echo "$usage"
			exit 1
    esac
done

if [[ $# == 0 ]]; then
	(>&2 echo "Argument <array_id> is required.")
	echo "$usage"
	exit 1
fi

anyId=$1
scriptDir="$(cd "$(dirname "${BASH_SOURCE[0]}" )" && pwd )"
phyId=$(${scriptDir}/ANY2PHY $anyId)
phyPathId=$(${scriptDir}/PHY2PATH $phyId)

if [[ $# == 2 ]]; then
    monId=$2
else
    monId=mon${phyPathId}
fi

echo "Adding a monitor interface for $anyId ($phyId), named $monId ..."
if [[ $(${scriptDir}/IsIntel5300NIC $anyId) == 1 ]]; then
    devId=$(${scriptDir}/ANY2DEV $anyId)
    ${scriptDir}/Stop_Monitor_Interface $phyId
    sudo iw $phyId interface add $monId type monitor
    sudo ifconfig $monId up
    sudo ifconfig $monId down
    sudo ifconfig $monId up
    sudo ifconfig $devId down
    sudo ifconfig $devId up
    sudo ifconfig $devId down # multiple up and down for IWL5300
    sudo iw $monId set freq 5200 HT20
    ${scriptDir}/Stop_Monitor_Interface $phyId
    sleep 1
fi
sudo iw $phyId interface add $monId type monitor
sudo ifconfig $monId up