#!/bin/bash

# Initial Author: D.Bienz
# Script is required to make the QCA7000 ICs running on the current board designs. The IC requires
# defined pull-push resistors on its local IOS like RESET or FLASH_BOOT. Since the current hardware design of the EVTEC
# boards don't provide any such, the QCAs won't start correctly on power up. In order to be able to use them, we have
# to reset them through the RESET GPIO, remove the kernel module, add the kernel module again and activate the IC through
# the RESET GPIO again.

# GPIOs addressing the pin GPIO0 of the QCA IC for Boot Source selection
QCA_FLASH_BOOT_GPIOS=(
  "/sys/class/gpio/gpio125/value"
  "/sys/class/gpio/gpio136/value"
  "/sys/class/gpio/gpio149/value"
  "/sys/class/gpio/gpio6/value"
)


# GPIOs addressing the RESET pin of the QCA IC
QCA_RESET_GPIOS=(
  "/sys/class/gpio/gpio123/value"
  "/sys/class/gpio/gpio134/value"
  "/sys/class/gpio/gpio142/value"
  "/sys/class/gpio/gpio143/value"
)

# The order of setting FLASH_BOOT and RESET is important!
# Therefore, the RESET pins are first set to low
echo "First set QCA RESET pins to low"
for i in "${QCA_RESET_GPIOS[@]}"; do
    echo "0" > $i
    if [ $? -eq 0 ]; then
        echo "Set $i to low"
    else
        echo "Failed to access $i. Maybe no GPIO exported?"
    fi
done

# Once the RESET pins are set to low, the FLASH_BOOT pins must be set to high
echo "Once RESET pins are low, we can set FLASH_BOOT pins to high"
for i in "${QCA_FLASH_BOOT_GPIOS[@]}"; do
    echo "1" > $i
    if [ $? -eq 0 ]; then
        echo "Set $i to high"
    else
        echo "Failed to access $i. Maybe no GPIO exported?"
    fi
done

# The RESET pins can be set to high again after the FLASH_BOOT pins were set to high before!
echo "Finally set RESET pins to high again (with FLASH_BOOT high as well)"
for i in "${QCA_RESET_GPIOS[@]}"; do
    echo "1" > $i
    if [ $? -eq 0 ]; then
        echo "Set $i to high"
    else
        echo "Failed to access $i. Maybe no GPIO exported?"
    fi
done

echo "Waiting for 2 seconds to let the QCA7000 ICs start"
sleep 2

# To let the QCA-SPI driver probe the devices properly again, we need to remove the kernel module and add it again
# Remove kernel driver module qca7000
rmmod qcaspi
if [ $? -eq 0 ]; then
    echo "Removed kernel module qcaspi successfully"
else
    echo "Unable to remove kernel module qcaspi"
fi

rmmod qca_7k_common
if [ $? -eq 0 ]; then
    echo "Removed kernel module qca_7k_common successfully"
else
    echo "Unable to remove kernel module qca_7k_common"
fi

# Insert kernel driver module qca7000 again
modprobe qcaspi
if [ $? -eq 0 ]; then
    echo "Added kernel module qcaspi successfully"
else
    echo "Unable to add kernel module qcaspi. Please check!"
fi

echo "QCA7000 Fix complete."