#!/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

if [ ! -f /target/etc/apt/sources.list ] ; then
    echo "apt-update: error: Missing /target/etc/apt/sources.list." >> $log
    exit 1
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

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 \
    update >> $log 2>&1
