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

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

command=${2}
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

# prepare a temporary apt.conf for the task

# NOTE #
# only works if Dir::Etc::SourceList is of the same distribution as the source list used by the hosts.
cat <<EOF > ${HERE}/apt.conf
Dir "."
{
  // Location of the state dir
  State "/var/lib/apt/" 
  {
     status "${HERE}/status";
  };
  
  // Location of the cache dir
  Cache "var/cache/apt/" {
     Archives "archives/";
     srcpkgcache "${HERE}/srcpkgcache.bin";
     pkgcache "${HERE}/pkgcache.bin";     
  };
  
  // Config files
  Etc "etc/apt/" {
     SourceList "/etc/apt/sources.list";
  };
};
Debug 
{
  NoLocking "true";
}
EOF

apt-get --config-file ${HERE}/apt.conf --download-only --yes ${command} || true

rm -rf ${HERE}
