#!/bin/sh

prereqs()
{
	# linux-firmware should run last since other hooks might add additional firmware
	for _req in "${0%/*}"/* ; do
		_script="${_req##*/}"
		if [ "${_script}" != "${0##*/}" ] ; then
			echo "${_script}"
		fi
	done
}

case "${1}" in
	prereqs)
		prereqs
		exit 0
		;;
esac

. /usr/share/initramfs-tools/hook-functions

test -d "${DESTDIR}"/lib/firmware || exit 0

prev_md5=
find "${DESTDIR}"/lib/firmware ! -empty -type f -exec md5sum -b {} + | sort | uniq -w32 -dD | \
	while IFS= read -r line ; do
		md5=$(printf '%s' "${line}" | cut -c -32)
		fw=$(printf '%s' "${line}" | cut -c 35-)
		if [ "${md5}" != "${prev_md5}" ] ; then
			tgt=${fw}
		else
			lnk=$(realpath --relative-to="${fw%/*}" "${tgt}")
			[ "${verbose}" = "y" ] && echo "Create firmware-link ${fw} -> ${lnk}"
			rm -f "${fw}"
			ln -s "${lnk}" "${fw}"
		fi
		prev_md5=${md5}
	done
