#!/bin/bash
# scpover v0.1
# Copyright (c) 2014 Daniel Lange, http://daniel-lange.com.
# Released into the public domain. NO LIABILITY ACCEPTED WHATSOEVER. USE AT YOUR OWN RISK.

READLINK="/bin/readlink"
TARGET=""


if [[ -v HOSTNAME ]] ; then
	case "${HOSTNAME,,}" in
		ashley)
			TARGET="marykate"
			;;
		marykate)
			TARGET="ashley"
			;;
		*)
			echo "Error: I have no cluster partner for ${HOSTNAME}. Exiting."
			exit 2
			;;
	esac
else
	echo "Error: I need \$HOSTNAME set to know where to copy."
	exit 1
fi

if [[ "$1" == "-h" || "$1" == "--help" ]] ; then
	echo "$0: <file1> [file2] ..."
	echo "  Copy files to the cluster partner via scp into the same directory as where is resides on the source host."
	echo "  Links (symbolic or hard) will be resolved and copied as a regular file. That's a feature/bug of scp."
	echo "  The target is determined from a pre-defined list built into the program. So don't specify one."
	echo "  HOSTNAME: ${HOSTNAME:-not set!}"
	exit 0
fi

if [[ ! -x $READLINK ]] ; then
	echo "ERROR: I need readlink to work. What strange system is this?"
	exit 3
fi

if [[ $# -lt 1 ]] ; then
	echo "I need at least one file to copy over to the cluster partner."
	exit 1
fi

echo "Copying from $HOSTNAME to $TARGET..."

for f in "$@"; do
	FULLNAME=""
	FULLNAME=$($READLINK -n -f "$f")
	if [[ -f "$f" ]] ; then
		echo "${FULLNAME} -> ${TARGET}:${FULLNAME%/*}/"
		scp -p -C "$f" "${TARGET}:${FULLNAME%/*}/"
	else
		echo "Warning: $f ($FULLNAME) is not a regular file. Skipping."
	fi
done
