#!/bin/sh

# Imports files from (future) dphys-config managed remote hosts into a
# local dphys-config repository.
#
# Copyright © 2011 Axel Beckert <abe@debian.org>
#
# This script is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This script is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this package; if not, write to the Free Software
# aFoundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA
#

VERSION=0.2

LIST="$1"
HOST="$2"
DIR="$3"

if [ -z "$LIST" -o -z "$HOST" -o -z "$DIR" ]; then
    if [ "$LIST" = "-v" -o "$LIST" = "--version" ]; then
	echo `basename $0`" version $VERSION"
	exit 0;
    fi
    echo `basename $0`" imports files from (future) dphys-config managed remote hosts into a local dphys-config(1) repository."
    echo "Usage: $0 <some-dphys-admin.list> [<user>@]<source-host> <output-directory>" 1>&2
    if [ "$LIST" = "-h" -o "$LIST" = "--help" ]; then
	exit 0;
    else
	exit 1;
    fi
fi

if echo "$LIST" | grep dphys-admin.list >/dev/null; then
    echo WARNING: dphys-config.list alike file name expected, but got dphys-admin.list alike file name. 1>&2
fi

egrep -v '^\s*$|^#' "$LIST" | \
    awk -F: '{print $2" "$1}' | \
    sed -e 's://:/:' | \
  while read dpath file; do
    if ssh "$HOST" "test -d '$dpath'" < /dev/null; then
	scp "$HOST:$dpath/$file" "$DIR/$file"
    else
	scp "$HOST:$dpath" "$DIR/$file"
    fi
done


