#!/bin/bash

usage="
        Usage: $(basename "$0") <array_id> <eval_string> [-h]
      Example: $(basename "$0") all sudo iw PHY set freq 5200
     Example1: $(basename "$0") 311 sudo iw PHY set freq 5200
     Example2: $(basename "$0") \"311 phy0\" iw PHY info
     Example3: $(basename "$0") \"311 mon4\" \"iw MON info 1>/dev/null\"
     Example4: $(basename "$0") \"wlp7s0 phy1\" \"echo PRODUCTNAME\" 2>/dev/null
Functionality: It executes the command string <eval_string> on each device of the array defined by <array_id>.

    <array_id> defines an Wi-Fi NIC array, which includes one or multiple Wi-Fi NICs.
    The parsing logic for <array_id> is as follows:
            if <array_id> == \"all\"         : an array including all detected Wi-Fi NICs
            if <array_id> is a PhyId       : an array of the specified device
            if <array_id> is a DeviceId    : an array of the specified device
            if <array_id> is a MonId       : an array of the specified device
            if <array_id> is a PhyPath     : an array of the specified device
            if <array_id> == \"array_id1 array_id2 etc...\" 
                                           : an array of the specified devices,
                                             each array_id* is resolved as above.
            if <array_id> == \"array_id1 array_id2 ... except array_id_n2 array_id_n3 etc\"
                                           : an array of the specified devices, but excluding the devices following the word \"except\".

    <eval_string> is the command string, it is mapped to each Wi-Fi NIC. 5 keywords (case-sensitive) appeared in <eval_string> are resolved automatically.
    5 keywords are: DEV (device logical name)
                    PHY (physical id)
                    MON (first monitor interface of the attached device)
                    PATH (PhyPath)
                    PRODUCTNAME (product name string)

    NOTICE: $(basename "$0") only detects PCI-E based Wi-Fi NICs, i.e., all USB based Wi-Fi NICs.

      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

function control-c {
    for job in $(jobs -p); do
        kill $job 1>/dev/null 2>/dev/null
    done
    exit 1
}

trap control-c SIGINT
trap control-c SIGTERM

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

expandArrayId() {
    local arrayId=$1
    local arrayIdList=""
    local phyList=""
    if [[ -f $arrayId ]]; then
        read -a arrayIdList <<< "$(cat $arrayId)"
    else if [[ $arrayId == "all" ]]; then
            arrayIdList=($(${scriptDir}/List_All_Phys))
         else
            echo $(${scriptDir}/ANY2PHY $arrayId)
            return
         fi
    fi
    
    echo ${arrayIdList[@]}
}

arrayId=$1
evalString="${@:2}"
arrayInclusionPart=$(echo $arrayId | sed -E "s/except.+//g")
arrayExclusionPart=$(echo $arrayId | grep -Eo except.+ | sed "s/except //g")
IFS=' ,' read -ra inclusionPartArray <<< "$arrayInclusionPart"
IFS=' ,' read -ra exclusionPartArray <<< "$arrayExclusionPart"

####### Handle Uniqueness
expandedInclusionArray=""
for symbol in "${inclusionPartArray[@]}"
do
    symbolExpansion=$(expandArrayId $symbol)
    expandedInclusionArray+=("$symbolExpansion")
done
uniqueInclusionArray=$(echo ${expandedInclusionArray[@]} | xargs -n1 | sort -u -k1)

####### Handle Exception
expandedExclusionArray=""
for symbol in "${exclusionPartArray[@]}"
do
    symbolExpansion=$(expandArrayId $symbol)
    expandedExclusionArray+=("$symbolExpansion")
done
uniqueExclusionArray=$(echo ${expandedExclusionArray[@]} | xargs -n1 | sort -u -k1)
xorArray="$(comm -2 -3 <(echo "${uniqueInclusionArray[@]}") <(echo "${uniqueExclusionArray[@]}"))"
# echo "${xorArray[@]}"
readarray -t lines <<< "${xorArray[@]}"

####### Core
for eachPhyId in "${lines[@]}"
do
    phyId=$eachPhyId
    deviceId=$(${scriptDir}/PHY2DEV $phyId)
    if [[ $phyId == "" ]]; then
        echo "unrecoginized phyId: $phyId"
        exit 1
    fi
    
    phyPath=$(${scriptDir}/PHY2PATH $phyId)
    monString=$(${scriptDir}/DEV2MON $deviceId)
    monId=$(echo $monString | head -n1)
    productName=$(${scriptDir}/GetPhyPathMapping | grep "PHY:$phyId " | grep -Eo 'PRODUCTNAME:.+' | sed -e 's:PRODUCTNAME\:::g')

    replaceDEV=$(sed "s/DEV/$deviceId/g" <<< $evalString)
    replacePHY=$(sed "s/PHY/$phyId/g" <<< $replaceDEV)
    replaceMON=$(sed "s/MON/$monId/g" <<< $replacePHY)
    replacePATH=$(sed "s/PATH/$phyPath/g" <<< $replaceMON)
    replaceProductName=$(sed "s#PRODUCTNAME#\"${productName}\"#g" <<< $replacePATH)
    finalString=$replaceProductName

    # echo "$finalString"
    eval "$finalString"

done

# Wait all subprocesses done.
for job in $(jobs -p); do
    wait $job
done