#!/bin/sh
#
# $dotat: scripts/sshtrace,v 1.4 2001/12/17 16:25:52 fanf Exp $

cat >/tmp/$$ <<-"EOF"

	# print ourself out twice: quoted and then in clear
	printme () {
		echo 'cat >/tmp/$$ <<-"EOF"'
		sed -e 's/^/	/' </tmp/$$
		echo EOF
		echo
		cat /tmp/$$	
		rm /tmp/$$
	}

	set -e

	# count hops and check max path length
	count=$1
	shift
	if [ $count -ge 30 ]; then echo Count exceeded.; exit; fi
	count=`expr $count + 1`

	# get local host information
	hostname=`hostname`
	address=`/usr/sbin/nslookup $hostname | sed -e '2d;/Address/!d;s/[^:]*:[ 	]*//'`
	echo $count $hostname $address

	# where is the route command?
	tryroute () { if [ -x $1 ]; then route=$1; fi; }
	route=x
	tryroute /sbin/route
	tryroute /usr/etc/route
	tryroute /usr/sbin/route
	if [ $route = x ]; then echo No route program.; exit; fi

	# work out where to hop next
	if [ $# -lt 1 ]; then echo Done.; exit; fi
	gateway=`$route get $1 | sed -e '/gateway/!d;s/[^:]*: //'`
	if [ "x$gateway" = "x" ]
	then
		# no gateway, so next hop will be the destination
		gateway=$1
		# and we'll want to trace from there to the next argument
		shift
	fi

	# go to next hop
	# echo printme '|' ssh -l root $gateway sh -s $count $*
	printme | ssh -x -o ForwardAgent=yes -l root $gateway sh -s $count $*
EOF

printme () {
	echo 'cat >/tmp/$$ <<-"EOF"'
	sed -e 's/^/	/' </tmp/$$
	echo EOF
	echo
	cat /tmp/$$	
	rm /tmp/$$
}

if [ $# -lt 1 ]
then
	# no args -- just print ourself out
	# so that we can be delivered to somewhere more useful
	printme
else
	# start the trace here
	printme | sh -s 0 $* `hostname`
fi
