#!/bin/sh -e

log=/var/log/messages

# The C.UTF-8 locale is not usable inside /target/.  Unset it here to avoid
# warnings like 'perl: warning: Setting locale failed.'.
if [ "$LANG" = "C.UTF-8" ] ; then
	unset LANG
fi

# Add to list of extra packages (to be) installed into /target/.
mkdir -p /var/lib/apt-install
touch /var/lib/apt-install/queue
for pkg in $@ ; do
    if ! grep -q "^$pkg$" /var/lib/apt-install/queue; then
        echo "$pkg" >> /var/lib/apt-install/queue
    fi
done

if [ ! -f /target/etc/apt/sources.list ] ; then
    # The package was only queued, and will be installed by the
    # postinst in base-installer.
    exit 1 # Return error as the package is not ready to be used yet.
fi

# Try to enable proxy when using HTTP.  What about using ftp_proxy for
# FTP sources?  (This code is in both apt-update and apt-install)
RET=`debconf-get mirror/protocol || true`
if [ "http" = "$RET" ]; then
    # try to find http proxy
    RET=`debconf-get mirror/http/proxy || true`
    if [ "$RET" ] ; then
	http_proxy="$RET"
	export http_proxy
    fi
fi

# Unset to avoid problems with packages using debconf.  This should
# avoid the following error when installing dash:
# "/var/lib/dpkg/info/ash/config: 1: Bad file descriptor"
# The problem only appear if /usr/share/debconf/confmodule is sourced
# into this script.
unset DEBIAN_HAS_FRONTEND
unset DEBIAN_FRONTEND
unset DEBCONF_FRONTEND
unset DEBCONF_REDIR

# first copy the files into /target/, then install in chroot
# environment.  This work around a bug in glibc, and make sure the
# packages run their postinst script in their target environment.

PATH=$PATH:/target/usr/bin:/target/bin:/target/usr/sbin:/target/sbin \
LD_LIBRARY_PATH=/usr/lib:/lib:/target/usr/lib:/target/lib \
/target/usr/bin/apt-get \
    -o Dir::State=/target/var/lib/apt \
    -o Dir::State::status=/target/var/lib/dpkg/status \
    -o Dir::Cache=/target/var/cache/apt \
    -o Dir::Etc=/target/etc/apt \
    -o Dir::Bin::methods=/target/usr/lib/apt/methods \
    -o Dir::Bin::gzip=/target/bin/gzip \
    -o Dir::Bin::dpkg=/target/usr/bin/dpkg \
    -o Dpkg::Options::=--root=/target \
    -y --download-only install $@ >> $log 2>&1

# Some packages (eg. the kernel-image package) require a mounted /proc/
# Only mount it if it isn't mounted already
if [ ! -f /target/proc/cmdline ] ; then
    mount -t proc proc /target/proc
fi

DEBIAN_FRONTEND=noninteractive \
chroot /target apt-get --no-download -y install $@ < /dev/null >> $log 2>&1

umount /target/proc

exit 0
