#!/bin/sh

## Copyright (c) 2010 Mykola Grechukh, Risc Group IT Solutions

## This program 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 3 of the License, or
## (at your option) any later version.
##
## This program 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 program; if not, write to the Free Software Foundation,
## Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
##

CONF=/etc/chain-ssh.conf

[ -f $CONF ] && . $CONF

usage() {
	echo "Usage: $0 [-t transport1,transport2,... ] {ssh|scp} .... ssh options ...."
	echo 
cat << EOF
e.g.: 

  $0 -t nagios@10.1.0.2,root@gw,guest@proxy scp user@server:file ./"

where 'gw', 'proxy', 'server' should be resolvable by /etc/hosts, 
DNS or ~/.ssh/config on localhost. For final destination, 
'server' - optionally it can be known only by 'proxy'

This tool of course could be used for scp, ssh and as a transport
for rsync:

 $0 -t root@someserver ssh user@remoteserver

  rsync -av -e '$0 -t user@noc,root@gw ssh' remoteserver:/path/to/ ./

On all intermediate servers should be installed program 'nc' or 
'netcat' or any replacement (tell which to use by -p key).
EOF

}

parse_transport_list() {
	for i in $(echo "$TRANSPORTLIST" | tr ',' '\n'); do
		TRANSPORT="$TRANSPORT ssh -At $VERBOSE $i"
	done
	TRANSPORT="$TRANSPORT $PROGRAM %h %p"
}

PROGRAM=nc

while :; do
	case "$1" in
		"-p")
			PROGRAM="$2"
			shift;shift
			;;
		"-t")
			TRANSPORTLIST="$2"
			shift;shift
			;;
		"-v"*|"-q")
			VERBOSE="$VERBOSE $1"
			shift
			;;
		ssh|scp)
			MODE=$1
			shift
			break
			;;
		*)
			usage && exit -2
			;;
	esac
done

parse_transport_list

$MODE -o ProxyCommand="$TRANSPORT" $*
