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

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

# For those who don't want to load any firmware, even if available on
# installation images (#1029848):

# Trisquel: hardcode disable firmware loading
# to prevent installation of nonfree blobs. This script
# is kept to preserve compatibility with hw-detect.
log "firmware lookup disabled (hardcoded), exiting"
exit 0

# 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):
for fw_dir in /firmware /cdrom/firmware; do
	if [ -d "$fw_dir/dep11" ]; then
		# Query only once:
		udevadm info --export-db | sed -n 's/.* MODALIAS=\(.*\)/\1/p' > /tmp/modalias.cache
		for patterns_file in "$fw_dir/dep11"/*.patterns; do
			if log-output -t install-firmware grep -f "$patterns_file" /tmp/modalias.cache; then
				package=$(basename "$patterns_file" .patterns)
				component=$(cat "${patterns_file%%.patterns}.component")
				log "detected the need for $package ($component) via modalias"
				find $fw_dir -name "${package}_*.deb" | while read deb; do
					mkdir -p /var/cache/firmware
					cp "$deb" /var/cache/firmware
					log "... added $deb to the firmware cache"
					echo $component >> /var/cache/firmware/components
					echo "$package $component modalias" >> /var/log/firmware-summary
				done
			fi
		done
		rm -f /tmp/modalias.cache
	fi
done

# Check whether microcode packages are desirable, based on CPU vendor.
# Only detect and queue installation: they aren't needed in the
# installer context, and they cannot be deployed via `dpkg -i` by the
# install-firmware hook due their dependencies; let the finish-install
# hook handle them instead. Note the component hardcoding.
printf "GenuineIntel intel-microcode\nAuthenticAMD amd64-microcode\n" | while read vendor pkg; do
	if grep -qs "^vendor_id.*$vendor$" /proc/cpuinfo; then
		log "queuing $pkg installation ($vendor)"
		echo $pkg >> /tmp/microcode.list
		mkdir -p /var/cache/firmware
