#!/bin/sh
#
#	update-via-ssh, perform the equivalent of an apt-get update
#	against the apt-walkabout instance, by using an account on a
#	remote system accessed using rsync over ssh.
#
set -e

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

if [ -r /etc/apt-walkabout.conf ]; then
    . /etc/apt-walkabout.conf 
fi

if [ -r etc/apt-walkabout.conf ]; then
    . etc/apt-walkabout.conf 
fi

# prompt for the remote system username and host name
name=${1:-${APT_WALKABOUT_REMOTE_HOST}}
if [ -z "${name}" ]; then
    if [ -z "${APT_WALKABOUT_REMOTE_HOST}" ]; then
        def=`hostname`
        echo -n "system name [${def}] ? "
        read name
        if [ -z "${name}" ]; then
            name=${def}
        fi
    else
        name=${APT_WALKABOUT_REMOTE_HOST}
    fi
fi

# location for the apt-walkabout instance on the remote system
HERE=tmp/apt-walkabout

# encapsulate sources.list into a environment variable
TEXT=`cat etc/apt/sources.list|tr '\n' '@'`

# create the remote apt-walkabout instance
ssh -C ${name} <<EOF
. .bashrc

set -e
HERE=\`pwd\`/${HERE}
mkdir -p \${HERE}
cd \${HERE}

mkdir -p etc/apt
mkdir -p var/lib/apt/lists/partial
mkdir -p var/lib/dpkg
mkdir -p var/cache/apt/archives/partial

echo ${TEXT}|tr '@' '\n' > etc/apt/sources.list

apt-get \
    -o Dir="." \
    -o Dir::Etc::SourceList=\${HERE}/etc/apt/sources.list \
    -o Dir::State::Lists=\${HERE}/var/lib/apt/lists/ \
    -o Dir::Cache::Archives=\${HERE}/var/cache/apt/archives \
    -o Dir::Cache::srcpkgcache=\${HERE}/srcpkgcache.bin \
    -o Dir::Cache::pkgcache=\${HERE}/pkgcache.bin \
    -o Debug::NoLocking=true \
    update
EOF

# grab back the lists
rsync -avPz --temp-dir=/tmp --compare-dest=/var/lib/apt/lists ${name}:${HERE}/var/lib/apt/lists var/lib/apt/
