#!/bin/sh
#
# ath10k-board BDF OUT NAME... -- write an ath10k board-2.bin (OUT) that
# holds the board data file BDF under each board NAME, e.g.
# "bus=snoc,qmi-board-id=ff,qmi-chip-id=30224".
#
# Why: the WCN399x of a phone has no board id programmed (qmi board_id
# 0xff), so ath10k takes the generic "bus=snoc,qmi-board-id=ff" entry of
# linux-firmware's board-2.bin -- the board data of another board, with
# which the WLAN firmware on hotdogb crashed ("CCPM: PLL lock failed").  The
# phone's own board data (its persist partition) stays on the phone; this
# file, under /run/makronix-firmware, is found before linux-firmware's.
#
# The format is ath10k's (drivers/net/wireless/ath/ath10k/hw.h,
# core.c ath10k_core_fetch_board_data_api_n): the magic
# "QCA-ATH10K-BOARD\0" padded to 4 bytes, then one ATH10K_BD_IE_BOARD (0)
# per name holding ATH10K_BD_IE_BOARD_NAME (0) and ATH10K_BD_IE_BOARD_DATA
# (1); every IE is id and length (little-endian 32 bit), its data padded
# to 4 bytes.

[ $# -ge 3 ] || { echo "usage: ath10k-board BDF OUT NAME..." >&2; exit 2; }
bdf=$1 out=$2
shift 2
[ -s "$bdf" ] || { echo "ath10k-board: no $bdf" >&2; exit 1; }

le32() {	# le32 N: N as 4 bytes, little-endian
	printf "\\$(printf %03o $(($1 & 255)))\\$(printf %03o $((($1 >> 8) & 255)))"
	printf "\\$(printf %03o $((($1 >> 16) & 255)))\\$(printf %03o $((($1 >> 24) & 255)))"
}
pad() {		# pad N: the zero bytes that bring N to a multiple of 4
	_p=$(( (4 - $1 % 4) % 4 ))
	while [ "$_p" -gt 0 ]; do printf '\000'; _p=$((_p - 1)); done
}
pad4() { echo $(( ($1 + 3) / 4 * 4 )); }

dlen=$(wc -c < "$bdf" | tr -d ' ')
tmp=$out.tmp
{
	printf 'QCA-ATH10K-BOARD\000'; pad 17
	for name in "$@"; do
		nlen=${#name}
		le32 0
		le32 $((8 + $(pad4 "$nlen") + 8 + $(pad4 "$dlen")))
		le32 0; le32 "$nlen"; printf '%s' "$name"; pad "$nlen"
		le32 1; le32 "$dlen"; cat "$bdf"; pad "$dlen"
	done
} > "$tmp" && mv "$tmp" "$out"
