#!/bin/sh
#===============================================================================
#
#  qualcomm-pre-up
#
#  Copyright (C) 2016 by Digi International Inc.
#  All rights reserved.
#
#  This program is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License version 2 as published by
#  the Free Software Foundation.
#
#
#  !Description: Load Qualcomm' wireless driver
#
#===============================================================================

[ "${IFACE}" != "wlan0" ] && exit 0

MACFILE="/lib/firmware/wlan/wlan_mac.bin"
TMP_MACFILE="$(mktemp -t wlan_mac.XXXXXX)"

# Read the MACs from DeviceTree. We can have up to four wireless interfaces
# The only required one is wlan0 that is mapped with device tree mac address
# without suffix.
for index in $(seq 0 3); do
	DT_WLANx_MAC="/proc/device-tree/wireless/mac-address"
	if [ "${index}" = "0" ]; then
		# Set a default MAC for wlan0
		MAC_ADDR="00:04:F3:FF:FF:FB"
	else
		# Add the interface suffix for the device tree node
		DT_WLANx_MAC=${DT_WLANx_MAC}${index}
		MAC_ADDR=""
	fi

	if [ -f "${DT_WLANx_MAC}" ]; then
		MAC_ADDR="$(hexdump -ve '1/1 "%02X" ":"' ${DT_WLANx_MAC} | sed 's/:$//g')"
	fi

	# Dump the MAC address in a file with the expected firmware format.
	#  example: Intf0MacAddress=0004f3fffffb
	echo "Intf${index}MacAddress=${MAC_ADDR}" | sed s/://g >> ${TMP_MACFILE}
done

# Override the MAC firmware file only if the MAC file has changed.
if ! cmp -s ${TMP_MACFILE} ${MACFILE}; then
	cp ${TMP_MACFILE} ${MACFILE}
fi
rm -f ${TMP_MACFILE}

# Check the version of modprobe installed to compound the arguments.
if readlink -f $(which modprobe) | grep -qs kmod; then
	MODPROBE_ARGS="-i"
fi
# Load the wireless module with the params defined in modprobe.d/qualcomm.conf
modprobe ${MODPROBE_ARGS} wlan

# Validate that firmware was loaded by checking if the interface is present.
if [ -d "/sys/class/net/${IFACE}" ]; then
	echo "Loading qca6564 module: [OK]"
else
	echo "Loading qca6564 module: [FAILED]"
	exit 1
fi
