#!/bin/sh
set -e
. /usr/share/debconf/confmodule

log () {
	logger -t install-firmware "$@"
}

# copy any loose firmware files to /target (incl. subdirs)
if [ -d /lib/firmware ]; then
	for f in /lib/firmware/*; do
		if [ -e "$f" ]; then
			mkdir -p /target/lib/firmware/
			cp -a "$f" /target/lib/firmware/
		fi
	done
fi

# queue firmware packages based on modalias info (#989863):
DEP11=/firmware/dep11
if [ -d "$DEP11" ]; then
	# Query only once:
	udevadm info --export-db | sed -n 's/.* MODALIAS=\(.*\)/\1/p' > /tmp/modalias.cache
	for patterns_file in "$DEP11"/*.patterns; do
		if log-output -t install-firmware grep -f "$patterns_file" /tmp/modalias.cache; then
			package=$(basename "$patterns_file" .patterns)
			log "detected the need for $package via modalias"
			find /firmware -name "${package}_*.deb" | while read deb; do
				mkdir -p /var/cache/firmware
				cp "$deb" /var/cache/firmware
				log "... added $deb to the firmware cache"
			done
		fi
	done
	rm -f /tmp/modalias.cache
fi

# enable non-free repository if any firmware / injected drivers are
# detected.
if [ -d /var/cache/firmware ]; then
	for deb in /var/cache/firmware/*.deb; do
		if [ -f "$deb" ]; then
			need_nonfree=1
		fi
	done
fi

if [ "$need_nonfree" ]; then
	db_set apt-setup/non-free true
fi
