#!/bin/sh
set -e
. /lib/chroot-setup.sh

packages=$@

queue=/var/lib/apt-install/queue

# If we don't have a working mirror yet, only queue the package;
# it will be installed later by the postinst in base-installer
if [ ! -e /target/etc/apt/sources.list ]; then
	# Add to list of extra packages to be installed into /target/.
	mkdir -p /var/lib/apt-install
	touch $queue
	for pkg in $packages; do
		if ! grep -q "^$pkg$" $queue; then
			logger -t apt-install "Queueing package $pkg for later installation"
			echo "$pkg" >> $queue
		fi
	done

	exit 1 # Return error as the package is not ready to be used yet.
fi

MULTICD=""
if [ $(grep "^deb cdrom:" /target/etc/apt/sources.list | wc -l) -gt 1 ]; then
	MULTICD=1
	log-output -t apt-install umount /cdrom || true
fi

ERRCODE=0
in-target sh -c "debconf-apt-progress --logstderr --no-progress -- apt-get -o APT::Install-Recommends=false -y --no-remove install $packages" || ERRCODE=$?

if [ "$MULTICD" ]; then
	load-install-cd "/target" || true
fi

if [ "$ERRCODE" != 0 ]; then
	exit 1
else
	exit 0
fi
