#!/bin/sh
#
#	fetch, downloads packages required ... using the package lists
#	on the host (not the pen drive, so that my apt-proxy is used),
#	using the target system's status file on the pen drive, into
#	the pen drive archives.  [while on either system]
#
set -ex

name=${1}
shift
if [ -z "${name}" ]; then
    def=`hostname`
    echo -n "system name [${def}] ? "
    read name
    if [ -z "${name}" ]; then
        name=${def}
    fi
fi

command="${*}"
shift
if [ -z "${command}" ]; then
    command="dist-upgrade"
fi

if [ ! -f bin/fetch ]; then
    echo "aborted, we're not in an apt-walkabout instance"
    exit
fi

if [ ! -f var/lib/dpkg/status.${name}.gz ]; then
    echo "aborted, we have no status file for system ${name}, do an adopt"
    exit
fi

HERE=/tmp/apt-walkabout.$$
mkdir ${HERE}

# extract the status file from our list of them
gzip --decompress --stdout var/lib/dpkg/status.${name}.gz > ${HERE}/status

rm -f ${HERE}/srcpkgcache.bin ${HERE}/pkgcache.bin

apt-get \
    -o Dir="." \
    -o Dir::Etc::SourceList=${PWD}/etc/apt/sources.list \
    -o Dir::State::Lists=${PWD}/var/lib/apt/lists/ \
    -o Dir::State::status=${HERE}/status \
    -o Dir::Cache::Archives=${PWD}/var/cache/apt/archives \
    -o Dir::Cache::srcpkgcache=${HERE}/srcpkgcache.bin \
    -o Dir::Cache::pkgcache=${HERE}/pkgcache.bin \
    -o Debug::NoLocking=true \
    -qq --print-uris \
    --download-only --yes ${command} > ${HERE}/uris

# uris list may be empty
cd ${PWD}/var/cache/apt/archives && puf `cut -f1 -d\' ${HERE}/uris` || true

rm -rf ${HERE}
