#!/bin/sh -ue
NAME=linux-firmware
VERSION=git
RELEASE=2
SOURCE="https://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git"

copy_fw_match() {
	_pattern="$1"
	find . \( -type f -o -type l \) -path "./$_pattern" | while IFS= read -r _fw; do
		_rel="${_fw#./}"
		_dst_dir="$PKG/lib/firmware/$(dirname "$_rel")"
		mkdir -p "$_dst_dir"
		cp -a "$_rel" "$_dst_dir/" || die "failed to copy $_rel"
	done
}

copy_fw_dir() {
	_dir="$1"
	[ -d "$_dir" ] || return 0
	_dst="$PKG/lib/firmware/$_dir"
	mkdir -p "$(dirname "$_dst")"
	cp -a "$_dir" "$_dst" || die "failed to copy $_dir"
}

install_whence_links() {
	[ -f WHENCE ] || return 0
	sed -n 's/^Link:[[:space:]]\+\([^[:space:]]\+\)[[:space:]]\+->[[:space:]]\+\([^[:space:]]\+\)$/\1 \2/p' WHENCE | \
	while IFS=' ' read -r _link _target; do
		[ -n "$_link" ] || continue
		_link_dir=$(dirname "$_link")
		_abs_target=$(readlink -m "$PKG/lib/firmware/$_link_dir/$_target")
		case "$_abs_target" in
			"$PKG/lib/firmware"/*)
				[ -f "$_abs_target" ] || [ -L "$_abs_target" ] || continue
				mkdir -p "$PKG/lib/firmware/$_link_dir"
				ln -sf "$_target" "$PKG/lib/firmware/$_link" || die "failed to link $_link"
				;;
		esac
	done
}

build() {
	msg "installing linux-firmware payload..."
	mkdir -p "$PKG/lib/firmware"

	cp -a WHENCE "$PKG/lib/firmware/" 2>/dev/null || true
	cp -a LICEN* "$PKG/lib/firmware/" 2>/dev/null || true
	cp -a regulatory.db regulatory.db.p7s "$PKG/lib/firmware/" 2>/dev/null || true
	#iwlwifi, i915, amdgpu
	copy_fw_match 'intel/iwlwifi/iwlwifi-*'
	copy_fw_match 'intel/iwlwifi/*.pnvm'
	[ -n "$(find "$PKG/lib/firmware/intel/iwlwifi" -type f -name 'iwlwifi-*' 2>/dev/null)" ] || \
		die "no iwlwifi firmware files were installed (source layout changed?)"
	copy_fw_dir i915
	copy_fw_dir amdgpu

	# atheros/qualcomm
	copy_fw_dir ath10k
	copy_fw_dir ath11k
	copy_fw_dir ath12k
	copy_fw_dir brcm

	# realtek
	copy_fw_dir rtl_bt
	copy_fw_dir rtlwifi
	copy_fw_dir rtw88
	copy_fw_dir rtw89

	# mediaTek
	copy_fw_dir mediatek
	install_whence_links

	mkdir -p "$PKG/usr/share/licenses/linux-firmware"
	[ -f WHENCE ] && install -m 0644 WHENCE "$PKG/usr/share/licenses/linux-firmware/WHENCE"
	msg "linux-firmware set: curated"
}

. ${0%/*}/../../libsh/libdmake.sh
