#!/bin/sh

# trsh -- execute from a remote shell with time out.
# version:1.21
# March. 22 2007
# Gouichi Iisaka <iisaka51@hotmail.com>

TRSH_TIMEOUT=${TRSH_TIMEOUT:-"1"}

SYSTEM=`uname -s`
case $SYSTEM in
HP-UX)	TRSH_RSH=${TRSH_RSH:-"/usr/bin/remsh"}
	PING=/usr/sbin/ping 
        PINGOPT="-n 1 -m ${TRSH_TIMEOUT}"
;;
*)	TRSH_RSH=${TRSH_RSH:-"/usr/bin/ssh -x "}
	PING=/bin/ping 
        PINGOPT="-c 1 -w ${TRSH_TIMEOUT}"
;;
esac

USAGE="Usage: trsh [-e <ssh|rsh>] [-t timeout] [-p port][-l user] host remote_cmd"
OPTIONS=`/usr/bin/getopt 'De:p:t:l:' "$@"`
# Note the quotes around '$OPTIONS': they are essential!
eval set -- '$OPTIONS'

OPT_PORT=""
OPT_USER=""
DEBUG=""

while true :
do
    case "$1" in
        -e) TRSH_RSH="$2" ; shift 2 ;;
        -p) OPT_PORT="-p $2" ; shift 2 ;;
        -l) OPT_USER="-l $2" ; shift 2 ;;
        -t) TRSH_TIMEOUT="$2" ; shift 2 ;;
        -D) DEBUG="ON" ; shift ;;
        --) shift ; break ;;
        *) echo ${USAGE} ; exit 1 ;;
    esac
done

[ "$DEBUG" = "ON" ] && {
    set -x
    echo "ARGV: $#"
    echo "ARGS: $@"
}

if [ "$#" -lt "2" ] ; then
	echo $USAGE ;  exit 1 
fi

HOST=$1 ; shift
$PING $HOST $PINGOPT >/dev/null 2>&1
RETVAL=$?
case $RETVAL in
0)	exec $TRSH_RSH $OPT_PORT $OPT_USER $HOST $@ ;;
1)	echo "${HOST}: Network unreachable!!" >&2 ;;
*)	echo "${HOST}: Time out!!" >&2 ;;
esac

exit $RETVAL
