#!/bin/sh -eu

# To re-generate the wifi-firmware.mk after having updated the Broadcom WiFi drivers,
# run the script $script_path_relative_to_repo inside this repo as follows:
# ./$script_path_relative_to_repo <bcm-sdk-path> <makefile-path>
# After that, verify whether the output is correct and fix the script, if it is not!
# If it is correct, verify that the file bcmkernel/wifi-firmware.mk is the new updated version.

log_error() {
    echo "$@" >&2
}

if [ $# -ne 2 ]; then
    log_error "Usage: $0 <bcm-sdk-directory> <makefile-path> "
    exit 1
fi

bcm_sdk_dir="$1"
makefile_path="$2"

if ! [ -d "$bcm_sdk_dir" ]; then
    log_error "$0: $bcm_sdk_dir is not a directory. Did you specify the right path to the BCM SDK?"
    exit 2
fi

if [ -z "$makefile_path" ]; then
    log_error "$0: makefile name must be specified."
    exit 3
fi

firmware_names="$(
    cd "$bcm_sdk_dir" && \
    find bcm963xx/bcmdrivers/broadcom/net/wl/impl*/sys/src/dongle/bin -type f -name rtecdc.bin | \
    awk -F'/' '{
        match($0, /impl([0-9]+)/, arr);
        impl = arr[1];
        if (match($0, /bin\/([^/]+)\/release\/rtecdc.bin$/, num)) {
            num_str = num[1];
        } else if (match($0, /bin\/([^/]+)\/rtecdc.bin$/, num)) {
            num_str = num[1];
        } else {
            next;
        }
        print num_str;
    }' | \
    sort | uniq
)"

script_git_repo="$(git -C "$(dirname "$0")" rev-parse --show-toplevel)"
script_path_relative_to_repo="$(realpath --relative-to="$script_git_repo" "$0")"
for fw_dir in $firmware_names; do
    # Define PKG_NAME and add package entry into the specified Makefile using echo commands
    {
    echo "#---"
    echo "define Package/bcm963xx-wifi-fw-$fw_dir"
    echo "	CATEGORY:=Base system"
    echo "	TITLE:=BCM963xx WiFi firmware for BCM$fw_dir"
    echo "	DEPENDS:=+bcm963xx-bsp"
    echo "endef"
    echo "define Package/bcm963xx-wifi-fw-$fw_dir/description"
    echo "	This package contains the WiFi firmware for BCM$fw_dir."
    echo "endef"
    echo "define Package/bcm963xx-wifi-fw-$fw_dir/install"
    echo "endef"
    echo "\$(eval \$(call BuildPackage,bcm963xx-wifi-fw-$fw_dir))"
    echo
    } >> "$makefile_path"
done
