#!/bin/sh
. ./01_SetVariables.sh
export PKGNAM=firmware-installer
export VERSION=15.0
export ARCH=noarch
export BUILD=1slint
rm -rf "$ROOTDIR"/firmware
mkdir "$ROOTDIR"/firmware
(cd /lib/modules/$KVER || exit
	find . -name '*.ko.zst'|while read -r i; do
	if modinfo "$i"|grep -q "^firmware"; then
		modinfo "$i"|grep "^firmware"|while read -r j; do
			printf "%b" "$i|"
			printf "%b" "${j}|"|sed 's#.* ##'
			modinfo "$i"|grep '^description'|sed 's#^description:    ##'   
			
		done
 	fi
done |sort > "$ROOTDIR"/firmware/firmware_by_module
)
(
cd "$ROOTDIR"/firmware || exit
sed '
\#/atm/#d
\#/crypto/#d
\#/gpu/#d
\#/hid/#d
\#/infiniband/#d
\#/isdn/#d
\#/media/#d
\#/mfd/#d
\#/can/softing/#d
\#/netronome/#d
\#/hamradio/#d
\#/scsi/#d
\#/tty/#d
\#/usb/host/#d
\#/usb/misc/#d
\#/usb/serial/#d
\#/video/#d
\#/sound/#d
\#/usb/storage/#d
/Driver for cx23885 based TV cards/d
' firmware_by_module > bof
 sed 's#[^|]*|\([^|]*\)|.*#\1#' bof > firmware_wanted
)
(cd /lib/firmware || exit
while read -r p; do
	find .|grep "$p"|sed 's#..##'
done < "$ROOTDIR"/firmware/firmware_wanted > "$ROOTDIR"/firmware/bof
)
(cd "$ROOTDIR"/firmware || exit
sort bof|uniq > firmware_to_extract
)
 while read -r i; do
	p=$(find /lib/firmware -name "$(basename "$i")"|grep "$i")
	if [ ! "$(LANG=C stat -c "%F" "$p")" = directory ]; then
		DIRNAME=$(dirname "$p"|sed 's#.##')
		mkdir -p $ROOTDIR/firmware/pkg/"$DIRNAME"
		cp "$p" $ROOTDIR/firmware/pkg/"$DIRNAME"/
	fi 
 done < $ROOTDIR/firmware/firmware_to_extract
(cd $ROOTDIR/firmware/pkg/lib/firmware/ || exit
for DUP in  mt7601u.bin.xz mt7662.bin.xz mt7662_rom_patch.bin.xz; do
	ln -s mediatek/$DUP $DUP
done
)
(cd $ROOTDIR/firmware/pkg
mkdir install
echo "firmware-installer: firmware-installer (firmware to allow a net install)" > install/slack-desc
/sbin/makepkg -l y -c n $ROOTDIR/packages/$PKGNAM-$VERSION-$ARCH-$BUILD.txz
)
