#!/bin/sh
#
# firmware-partitions -- make the firmware in the phone's own partitions
# visible to the kernel's firmware loader, before the drivers that need it
# load.  For each line of /etc/makronix/firmware-partitions
# (PARTITION DIR PATH): mount PARTITION of the active slot read-only under
# /run/makronix-partitions/PARTITION, and link FW/PATH to its DIR, with
# FW=/run/makronix-firmware; then put FW first in the loader's search path
# (the firmware_class.path parameter; /usr/lib/firmware stays the fallback).
#
# Runs in stage 1, before udev: the partitions are found by their GPT name
# in sysfs (PARTNAME), not by /dev/disk/by-partlabel, which udev makes.  The
# active slot is the one qcom-ab-slot names active (the ABL passes no slot on
# the command line); "a" when that fails.

CONF=/etc/makronix/firmware-partitions
FW=/run/makronix-firmware
MNT=/run/makronix-partitions
PARAM=/sys/module/firmware_class/parameters/path

[ -r "$CONF" ] || exit 0

slot=$(/usr/bin/qcom-ab-slot status 2>/dev/null |
    awk '/ active=1 / { sub(":.*", "", $1); sub("^boot_", "", $1); print; exit }')
[ -n "$slot" ] || slot=a

# partdev NAME: the block device whose GPT name is NAME
partdev() {
	for _u in /sys/class/block/*/uevent; do
		if grep -qx "PARTNAME=$1" "$_u"; then
			_d=${_u%/uevent}
			echo "/dev/${_d##*/}"
			return 0
		fi
	done
	return 1
}

status=0
while read -r part dir path; do
	case $part in ''|'#'*) continue ;; esac
	dev=$(partdev "${part}_$slot") || dev=$(partdev "$part") ||
		{ echo "firmware-partitions: no partition $part" >&2; status=1; continue; }
	m=$MNT/$part
	mkdir -p "$m" "$FW/$(dirname "$path")"
	if ! grep -q " $m " /proc/mounts; then
		mount -o ro,nosuid,nodev,noexec "$dev" "$m" ||
			{ echo "firmware-partitions: cannot mount $dev" >&2; status=1; continue; }
	fi
	ln -sfn "$m/$dir" "$FW/$path"
	echo "firmware-partitions: $FW/$path -> $dev ($part, slot $slot)" > /dev/kmsg
done < "$CONF"

[ -w "$PARAM" ] && printf '%s' "$FW" > "$PARAM"
exit $status
