#!/bin/sh

[ -e /lib/firmware/$FIRMWARE ] && exit 0

. /lib/functions.sh
. /lib/functions/system.sh

ath11k_generate_macs() {
	touch /lib/firmware/ath11k-macs
	eth=$(cat /sys/class/net/eth0/address)
	mac1=$(macaddr_add $eth 2)
	mac2=$(macaddr_add $eth 10)
	mac3=$(macaddr_add $eth 18)
	echo -ne \\x${mac1//:/\\x} >> /lib/firmware/ath11k-macs
	echo -ne \\x${mac2//:/\\x} >> /lib/firmware/ath11k-macs
	echo -ne \\x${mac3//:/\\x} >> /lib/firmware/ath11k-macs
}

ath11k_generate_macs_wf194() {
	touch /lib/firmware/ath11k-macs
	mac=$(grep BaseMacAddress= /dev/mtd14 | cut -dx -f2)
	eth=$(macaddr_canonicalize $mac)
	mac1=$(macaddr_add $eth 2)
	mac2=$(macaddr_add $eth 10)
	mac3=$(macaddr_add $eth 18)
	echo -ne \\x${mac1//:/\\x} >> /lib/firmware/ath11k-macs
	echo -ne \\x${mac2//:/\\x} >> /lib/firmware/ath11k-macs
	echo -ne \\x${mac3//:/\\x} >> /lib/firmware/ath11k-macs
}

caldata_die() {
        echo "caldata: " "$*"
        exit 1
}

caldata_extract() {
        local part=$1
        local offset=$(($2))
        local count=$(($3))
        local mtd

        mtd=$(find_mtd_chardev $part)
        [ -n "$mtd" ] || caldata_die "no mtd device found for partition $part"

        dd if=$mtd of=/lib/firmware/$FIRMWARE iflag=skip_bytes bs=$count skip=$offset count=1 2>/dev/null || \
                caldata_die "failed to extract calibration data from $mtd"
}

board=$(board_name)

case "$FIRMWARE" in
"ath11k/IPQ8074/hw2.0/caldata.bin")
	case "$board" in
	cig,wf194c|\
	cig,wf194c4|\
	edgecore,eap102 |\
	edgecore,eap106 |\
	octogate,ax-3500|\
	qcom,ipq807x-hk01|\
	qcom,ipq807x-hk14|\
	tplink,ex227|\
	tplink,ex447|\
	sercomm,wallaby|\
	yuncore,ax860)
                caldata_extract "0:ART" 0x1000 0x20000
		;;
	esac
	;;
"ath11k/IPQ6018/hw1.0/caldata.bin")
	case "$board" in
	cig,wf188|\
	cig,wf188n|\
	edgecore,eap101|\
	hfcl,ion4xi|\
	hfcl,ion4xe|\
	octogate,ax-3000|\
	wallys,dr6018|\
	wallys,dr6018-v4|\
	qcom,ipq6018-cp01|\
	xiaomi,ax1800|\
	yuncore,ax840)
                caldata_extract "0:ART" 0x1000 0x20000  
		;;
	esac
	;;
ath11k/QCN9074/hw1.0/caldata_1.bin)
	case "$board" in
	qcom,ipq807x-hk14)
                caldata_extract "0:ART" 0x26800 0x20000  
		;;
	esac
	;;
ath11k/QCN9074/hw1.0/caldata_2.bin)
	case "$board" in
	qcom,ipq807x-hk14|\
	qcom,ipq5018-mp03.3)
                caldata_extract "0:ART" 0x4C000 0x20000  
		;;
	esac
	;;
ath11k-macs)
	case "$board" in
	edgecore,eap101|\
	edgecore,eap102|\
	edgecore,eap106|\
	cig,wf188n)
		ath11k_generate_macs
		;;
	cig,wf194c|\
	cig,wf194c)
		ath11k_generate_macs_wf194
		;;
	esac
	;;
*)
	exit 1
	;;
esac
