#!/bin/sh
#
#	apt-walkabout fetch [TARGET] [COMMAND]
#
#	Downloads packages required for a target system to do an
#	upgrade.  Uses the package lists and the target system's
#	status file on the apt-walkabout instance, and saves the
#	packages into the apt-walkabout package cache.
#
#	Run this on any system.
#	Run this after you have done an "apt-walkabout adopt".
#
set -e

if [ ! -f bin/fetch ]; then
    echo "apt-walkabout: aborted, not in an apt-walkabout package cache"
    exit 1
fi

name=${1}
shift || true
if [ -z "${name}" ]; then
    # default name to the only known target system if there is one
    echo -n "apt-walkabout: informational, known target systems are: "
    count=0
    for host in `find var/lib/dpkg/ -maxdepth 1 -name "status.*.gz" -printf "%f\n"|cut -f2 -d.` ; do
	name=${host}
	echo -n "${host} "
	count=$(($count + 1))
    done
    if [ $count -eq 0 ]; then
	echo "(none at all)"
	echo "apt-walkabout: aborted, cannot run without known target systems, do an adopt"
	exit 1
    fi
    echo
    if [ $count -ne 1 ]; then
	# otherwise ask for target system name
	def=${name}
	echo -n "target system name [${def}] ? "
	read name
	if [ -z "${name}" ]; then
	    name=${def}
	fi
    else
	echo "apt-walkabout: warning, defaulted to target system: ${name}"
    fi
else
    echo "apt-walkabout: informational, target system: ${name}"
fi

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

command="${*}"
shift || true
if [ -z "${command}" ]; then
    command="dist-upgrade"
    echo "apt-walkabout: warning, defaulted to command: ${command}"
else
    echo "apt-walkabout: informational, command: ${command}"
fi

# create a temporary directory for context
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

# destroy any prior apt package cache file
rm -f ${HERE}/srcpkgcache.bin ${HERE}/pkgcache.bin

# do download of files required
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 \
    --download-only --yes ${command} || true

# delete the temporary directory
rm -rf ${HERE}

echo "apt-walkabout: success, fetch for ${name} completed"
exit 0
