#!/bin/sh

SERVER=${TPKG_SERVER:-"ftp://ftp.debian.org"}
TDIR=`mktemp -t -d tpkg-install-libc.XXXXXXXXXX`

# $1 is the architecture name
archname=$1
debarch=`tpkg-debarch $1`
debgnuarch=`dpkg-architecture -f -a$debarch -qDEB_HOST_GNU_TYPE 2>/dev/null`

DEFAULTLIBSET='libdb1-compat$ libc6$ libc6.*-dev$ linux-kernel-headers$'

echo 'deb "' $debarch '"'

case $debarch in
    alpha)
	DEFAULTLIBSET='libdb1-compat$ libc6.[0-9]*$ libc6.[0-9]*-dev$ linux-kernel-headers$' ;;
    ia64)
	DEFAULTLIBSET='libdb1-compat$ libc6.[0-9]*$ libc6.[0-9]*-dev$ linux-kernel-headers$' ;;
    sparc)
	DEFAULTLIBSET='libdb1-compat$ libc6$ libc6.*-dev$ linux-kernel-headers$ libc6.*-sparcv9$ libc6.*-dev-sparcv9$ libc6.*-sparcv9b$ libc6.*-dev-sparcv9b$ libc6.*-sparc64$ libc6.*-dev-sparc64$ lib64gcc1$' ;;
    s390)
	DEFAULTLIBSET='libdb1-compat$ libc6$ libc6.*-dev$ linux-kernel-headers$ libc6-s390x$ libc6-dev-s390x$' ;;
    unknown)
	echo "Hmph - dunno the $1 arch" >&2
	exit 2
esac

# $2 are the (optional) library names
if [ $# -ge 2 ]; then
    LIBSET=$2
else
    LIBSET=${LIBSET:-$DEFAULTLIBSET}
fi

wget $SERVER/debian/dists/testing/main/binary-${debarch}/Packages.gz -O $TDIR/packageset.gz || exit 2

rm -f $TDIR/packageset
gzip -d $TDIR/packageset.gz || exit 2

DOWNLOADEDDEBS=""
for PATTERN in $LIBSET
do
        debfilename=`dpkg-awk -f $TDIR/packageset "Package:"$PATTERN -- "Filename" | sed --silent 's/Filename: \(.*\)$/\1/gp'`
	for deb in $debfilename
	do
	  DEBHERENAME=$TDIR/`basename $deb`
	  wget $SERVER/debian/${deb} -O $DEBHERENAME || exit 2
	  DOWNLOADEDDEBS="$DOWNLOADEDDEBS $DEBHERENAME"
	done
done
dpkg-cross -a ${debarch} -i $DOWNLOADEDDEBS || exit 2

if [ $debgnuarch != $archname ]; then
    ln -s $debgnuarch /usr/$archname
fi

rm -r $TDIR
