#!/bin/sh
#
#	apt-walkabout put
#
#	Make a copy of an apt-walkabout package cache over SSH
#
set -e

# abort if we are already in an instance
if [ ! -f bin/apply ]; then
    echo "apt-walkabout: aborted, we're not in an apt-walkabout instance"
    exit 1
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 temporary instance on this system
HERE=apt-walkabout-tmp-put

# location for the apt-walkabout instance on the remote system
THERE=tmp/`basename $PWD`

# delete any previous attempt
rm -rf ${HERE}

# make a temporary tree
mkdir -p ${HERE}
cd ${HERE}

# create required directory structure
mkdir -p etc/apt
mkdir -p var/lib/apt/lists/partial
mkdir -p var/lib/dpkg
mkdir -p var/cache/apt/archives/partial

# copy the scripts, but only those expected to be needed
mkdir bin
cp --preserve=mode \
    ../bin/adopt \
    ../bin/apply \
    ../bin/update \
    ../bin/poll \
    ../bin/fetch \
    ../bin/each \
    bin/

# copy the sources list
cp ../etc/apt/sources.list etc/apt

# copy the status files
cp ../var/lib/dpkg/status*gz var/lib/dpkg/

# create our own lock file
touch var/lib/apt/lists/lock

cd ..

# copy the instance to remote directory
echo rsync -avPz ${HERE}/ ${name}:${THERE}
rsync -avPz ${HERE}/ ${name}:${THERE}

# remove the instance
rm -rf ${HERE}

exit 0
