#!/bin/sh
set -e

deb_package () {
	udpkg -f "$1" | grep '^Package:' | sed -e 's/package: *//'
}

# install cached firmware debs
if [ -d /var/cache/firmware ]; then
	for deb in /var/cache/firmware/*.deb; do
		if [ -f "$deb" ]; then
			cp -a "$deb" /target/tmp
			# TODO debconf passthrough
			# TODO maybe use apt-get -y install ./$(basename "$deb") to get dependency resolution (e.g. intel-microcode)
			if ! in-target dpkg -i "/tmp/$(basename "$deb")"; then
				# dpkg failed, force removal of package
				in-target dpkg --force-depends --remove "$(deb_package "$deb")" || true
			fi
			rm -f "/target/tmp/$deb"
		fi
	done
fi
