#!/bin/sh
set -e

deb_package () {
	ar p "$1" control.tar.gz | tar zxO ./control | 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
			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
