#!/bin/sh
set -e

# check environment variables are set
if [ -z "$CC03_ROOT" ]; then
    echo "Error: CC03_ROOT not set, nothing done"
    exit 1
fi
${CC03_ROOT}/bin/cc03-check

# set the test host IP address (as it happens, the MAC address of the
# author's test host is recognised by the DHCP server, and so the same
# IP address is allocated each time.  Use "ifconfig eth0" on the test
# host to find it's IP address.)
TARGET=${CC03_TARGET}
ESCAPED_TARGET=`echo $CC03_TARGET|sed 's/\./\\\./g'`

# remove the test host from our known keys (as it will have a changed
# key as a result of booting Knoppix and running sshstart)
echo "cc03-fetch: removing test host from our known keys"
grep -v "${ESCAPED_TARGET}" ~/.ssh/known_hosts > ~/.ssh/known_hosts.new && \
  mv -v ~/.ssh/known_hosts.new ~/.ssh/known_hosts

# check that you have a key
if [ ! -f ~/.ssh/id_dsa.pub ]; then
  echo "cc03-fetch: bailing out, you have no key, maybe 'ssh-keygen -t dsa'"
  exit
fi

# send our public key to the test host to let it authorise us silently
# (you will be prompted for the password)
echo "cc03-fetch: sending our public key to test host"
cat ~/.ssh/id_dsa.pub | \
  ssh -o StrictHostKeyChecking=no root@${CC03_TARGET} \
    "mkdir -p .ssh;cat >> .ssh/authorized_keys"

# c. setup and start the rsync daemon
# (we set it up by sending a configuration file to the test host)
echo "cc03-fetch: setting up rsync module list"
cat <<EOF | ssh root@${CC03_TARGET} "cat > /etc/rsyncd.conf"
[cdrom]
        path = /cdrom
        uid = root
        gid = root

[KNOPPIX]
        path = /KNOPPIX
        uid = root
        gid = root

[etc]
        path = /etc
        uid = root
        gid = root
EOF
# (if rsync's stdin is not redirected to /dev/null it will think it is
# being started from inetd and begin rsync protocol negotiation)
echo "cc03-fetch: starting rsync daemon"
ssh root@${CC03_TARGET} "rsync --daemon < /dev/null"

# d. copy the inner filesystem
# (this same command can be used to quickly restore the filesystem to
# the original state)
echo "cc03-fetch: copy inner filesystem"
mkdir -p ${CC03_PART}/knx/source/KNOPPIX && \
  rsync --archive --verbose --delete \
    rsync://${CC03_TARGET}/KNOPPIX ${CC03_PART}/knx/source/KNOPPIX

# e. copy (or return to original state) the outer filesystem
echo "cc03-fetch: copy outer filesystem"
mkdir -p ${CC03_PART}/knx/master/KNOPPIX && \
  rsync --archive --verbose --delete --exclude KNOPPIX/KNOPPIX \
    rsync://${CC03_TARGET}/cdrom ${CC03_PART}/knx/master/
