#!/bin/bash

usage="
        Usage: $(basename "$0") [firmware-code] [-h]
      Example: $(basename "$0") csi  #<-- switch the iwlwifi-5000 firmware to CSI measurement enabled version.
Functionality: This script switches the Wi-Fi iwlwifi-5000 firmware between the ordinary and the CSI measurement enabled.
               If [firmware-code] does not appear, this script will pop a menu and user choose the desired firmware.
               if [firmware-code] is \'csi\' or any other string, 
                     the script will switch the firmware to CSI measurement enabled version 
                                                            or the plain ordinary version, respectively.

      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

switchCode=$1

scriptDir="$(cd "$(dirname "${BASH_SOURCE[0]}" )" && pwd )"
csiVersionPath="${scriptDir}/iwlwifi-5000-2.ucode.sigcomm2010"
ordinaryVersionPath="${scriptDir}/iwlwifi-5000-5.ucode"
firmwarePath="/lib/firmware"
currentPath="$(find $firmwarePath -name 'iwlwifi-5000*')"
currentSize="$(stat --printf="%s" $currentPath)"


# echo $csiVersionPath
# echo $ordinaryVersionPath
# echo $firmwarePath
# echo $currentPath
# echo $currentSize

if [ -z "$switchCode" ]; then
    if [ $currentSize != $((336252)) ]; then
        echo "Current iwlwifi firmware is plain ordinary version,"
        decision="csi"
    else
        echo "Current iwlwifi firmware is CSI measurement version,"
        decision="plain"
    fi
else
    if [ "$switchCode" == "csi" ]; then
        decision="csi"
    else
        decision="plain"
    fi
fi

if [ $decision == "csi" ]; then
        echo "Switching to CSI measurement version..."
        sudo rm $currentPath
        sudo cp $csiVersionPath $firmwarePath/iwlwifi-5000-2.ucode
    else
        echo "Switching to plain ordinary measurement version..."
        sudo rm $currentPath
        sudo cp $ordinaryVersionPath $firmwarePath/iwlwifi-5000-5.ucode
fi

echo "Reloading iwlwifi module ..."
sudo modprobe -rf iwlwifi iwldvm 1>/dev/null 2>/dev/null
sleep 1
sudo modprobe iwlwifi

rm -rf /mnt/psrd/*