#!/bin/bash

usage="
        Usage: $(basename "$0") <arrayId> [freq] [-h]
      Example: $(basename "$0") all 5200
      Example: $(basename "$0") all '5200 HT20'
Functionality: It is a one-step preperation for CSI measurement for the array.
               Its maps internal jobs including (kill network-manager, disconnecting Wi-Fi, 
                  stop/restart monitor interface, changing mac address, and set frequency) 
                  to each device in the array <arrayId>.
               If [freq] is not specified, '5200 HT20' is the default.
               For possible <arrayId> definition, please refer to \"array_eval -h\".

      Options:
           -h         Show usage information
"

inputArray=$1
workingFreq='5200 HT20'

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

if [[ $# < 1 ]]; then
	(>&2 echo "arrayId are mandatory.")
	echo "$usage"
	exit 1
fi

if [[ $# == 1 ]]; then
    echo "Default working freq is $workingFreq."
elif [[ $# == 2 ]]; then
    workingFreq=$2
else
    echo "Too many parameters(The number of parameters is greater than two)."
	echo "$usage"
	exit 1
fi

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

scriptDir="$(cd "$(dirname "${BASH_SOURCE[0]}" )" && pwd )"

echo "Attempt changing CPU frequency governor to performance ..."
${scriptDir}/ChangeCPUFreqGovernor performance

echo "Un-managing NICs from Network-Manager ..."
${scriptDir}/Network-Manager_Unmanaged-for-Array "$inputArray"

echo "Unlocking RF-Kill..."
rfkill unblock wifi
${scriptDir}/array_eval "$inputArray" "rfkill unblock \$(rfkill list 2>/dev/null| grep PHY | sed -E 's/:.+//g' 2>/dev/null)"

echo "Disabling power management..."
${scriptDir}/array_eval "$inputArray" "sudo iw DEV set power_save off"

echo "Disconnecting Wi-Fi..."
${scriptDir}/array_eval "$inputArray" "sudo iw DEV disconnect 2>/dev/null"

echo "Stopping monitor interfaces..."
${scriptDir}/array_eval "$inputArray" "${scriptDir}/Stop_Monitor_Interface PHY"

echo "Changing MAC address..."
${scriptDir}/array_eval "$inputArray" "${scriptDir}/Set_Mac_Address_For_Device DEV"

echo "Adding monitor interfaces..."
${scriptDir}/array_eval "$inputArray" "${scriptDir}/AddMonitorInterface PHY"

echo "Changing working frequency to $workingFreq ..."
${scriptDir}/array_eval "$inputArray" "sudo ifconfig DEV down"
${scriptDir}/array_eval "$inputArray" "sudo iw MON set freq $workingFreq"
# Never try adding 'DEV UP'! It will make IWL5300 fail to receive packets in monitor mode.
# echo "Adding default route ..."
# ${scriptDir}/array_eval "$inputArray" "sudo ifconfig DEV up"
# ${scriptDir}/array_eval "$inputArray" "sudo route add default DEV"

echo "Preparation is done."

${scriptDir}/array_status all
