#!/bin/bash

WARN=0
DATE=$(date +%F-%T)

if grep -q '^wifi_hotspot_capacity_rpi_fix: False' /etc/iiab/local_vars.yml ; then
    echo "'wifi_hotspot_capacity_rpi_fix: False' found in /etc/iiab/local_vars.yml"
    echo "...so WiFi firmware will NOT be checked or replaced."

    exit 0
fi

echo -e "'wifi_hotspot_capacity_rpi_fix: True' presumed..."
echo -e "...in /etc/iiab/local_vars.yml (or /opt/iiab/iiab/vars/default_vars.yml ?)\n"

if ! $(diff -q /lib/firmware/brcm/brcmfmac43455-sdio.bin.iiab /lib/firmware/brcm/brcmfmac43455-sdio.bin); then
    mv /lib/firmware/brcm/brcmfmac43455-sdio.bin /lib/firmware/brcm/brcmfmac43455-sdio.bin.$DATE
    cp /lib/firmware/brcm/brcmfmac43455-sdio.bin.iiab /lib/firmware/brcm/brcmfmac43455-sdio.bin
    echo "Replacing /lib/firmware/brcm/brcmfmac43455-sdio.bin"
    WARN=1
fi

if ! $(diff -q /lib/firmware/brcm/brcmfmac43455-sdio.clm_blob.iiab /lib/firmware/brcm/brcmfmac43455-sdio.clm_blob); then
    mv /lib/firmware/brcm/brcmfmac43455-sdio.clm_blob /lib/firmware/brcm/brcmfmac43455-sdio.clm_blob.$DATE
    cp /lib/firmware/brcm/brcmfmac43455-sdio.clm_blob.iiab /lib/firmware/brcm/brcmfmac43455-sdio.clm_blob
    echo "Replacing /lib/firmware/brcm/brcmfmac43455-sdio.clm_blob"
    WARN=1
fi

if ! $(diff -q /lib/firmware/brcm/brcmfmac43430-sdio.bin.iiab /lib/firmware/brcm/brcmfmac43430-sdio.bin); then
    mv /lib/firmware/brcm/brcmfmac43430-sdio.bin /lib/firmware/brcm/brcmfmac43430-sdio.bin.$DATE
    cp /lib/firmware/brcm/brcmfmac43430-sdio.bin.iiab /lib/firmware/brcm/brcmfmac43430-sdio.bin
    cp /lib/firmware/brcm/brcmfmac43430-sdio.clm_blob.iiab /lib/firmware/brcm/brcmfmac43430-sdio.clm_blob
    echo "Replacing /lib/firmware/brcm/brcmfmac43430-sdio.bin"
    WARN=1
fi

if ! $(diff -q /lib/firmware/brcm/brcmfmac43430-sdio.clm_blob.iiab /lib/firmware/brcm/brcmfmac43430-sdio.clm_blob); then
    mv /lib/firmware/brcm/brcmfmac43430-sdio.clm_blob /lib/firmware/brcm/brcmfmac43430-sdio.clm_blob.$DATE
    cp /lib/firmware/brcm/brcmfmac43430-sdio.clm_blob.iiab /lib/firmware/brcm/brcmfmac43430-sdio.clm_blob
    echo "Replacing /lib/firmware/brcm/brcmfmac43430-sdio.clm_blob"
    WARN=1
fi

if [ "$WARN" = "1" ]; then
    echo -e "\n \033[31;5mWiFi Firmware has been replaced, per iiab/iiab#823.\033[0m"
    echo -e " \033[31;5mReboot is required to activate.\033[0m\n"
    touch /.fw_replaced
    #echo "rebooting..."
    #reboot
else
    echo -e " WiFi Firmware check \033[32;5mPASSED\033[0m, per iiab/iiab#823."
    echo -e " (Assuming you've rebooted since it was replaced!)\n"
    if [ -f /.fw_replaced ]; then
        rm /.fw_replaced
    fi
fi

# exit 0
