#!/bin/sh -

SSH='ssh -q -x'
RSYNC='rsync -Pv'
SAFE='timeout -v -s TERM -k 5s 3m'

# xfertest - test and time a network file transfer
# Steve Kinzler, steve@kinzler.com, Apr 25
# https://kinzler.com/me/home.html#unix

case "$1,$#" in
*,5|globus,3)	;;
*)	echo "usage: $0 method n_bytes local_srcdir desthost destdir"	  1>&2
	echo "       $0 globus src_ep:src_filepath dest_ep:dest_filepath" 1>&2
	echo 'methods: scp ssh rsync rsyncd' 1>&2; exit 1;;
esac
case "$1" in scp|ssh|rsync|rsyncd|globus) ;; *)
	echo "$0: unknown method ($1)"		    1>&2; exit 2;;
esac

case "$1" in globus)
	echo "### Copying $2 to $3 with $1 ..."
	out=`globus transfer "$2" "$3"`
	id=`echo "$out" | sed -n 's/^.*ID: *//p'`
	case "$id" in '') echo "$out"; exit 3;; esac
	/bin/echo -n "### Waiting for $1 task $id "
	globus task wait -H "$id"
	globus task show    "$id"
	echo "### To delete the transfer copy, run: globus delete '$3'"
	exit;;
esac

file=xfertest-file-$$

test -d "$3" -a -w "$3" || { echo "$0: local_srcdir not writable ($3)" 1>&2
			     exit 4; }
trap "rm -f '$3/$file'; exit \$ret" 0 1 2 3 15
echo "### Creating random $2-byte file in $3 ..."
time head -c "$2" /dev/urandom > "$3/$file" || { ret=5; exit 5; }

trap "rm -f '$3/$file'; $SAFE $SSH '$4' rm -f '$5/$file';exit \$ret" 0 1 2 3 15
echo "### Copying file to $4:$5 with $1 ..."
case "$1" in
scp)	time scp	      "$3/$file" "$4:$5";;
ssh)	time $SSH "$4" "cat > '$5/$file'" < "$3/$file";;
rsync)	time $RSYNC -e "$SSH" "$3/$file" "$4:$5";;
rsyncd)	time $RSYNC	      "$3/$file" "$4::$5";;
esac
