#!/bin/sh

# rcmds
#	excutes command on $HOSTS
#   Mon Feb 27 10:01:42 CET 2006
#   Fri Jan  5 10:41:34 CET 2007
#
# REQUIRES
#	fping from http://www.fping.com/
#	Or native ping if has -c -w options
#	.rhosts or authorized_keys/ssh-agent
#
# EXAMPLE
#	rcmds -s -- killall emacs
#
# ENVIRONMENT
#	HOSTS	List of space separated hostnames
#	RSH_CLIENT	rsh client. Defaults to rsh unless "-s" is used	

HOSTS=${HOSTS:="setme"}
HOSTNAME=`hostname`

if [ "$HOSTS" = "setme" ]
then
	HOSTS=`awk '/^192.*atpc-/{print $3}' /etc/hosts`
fi

TIMEOUT=0

CMD=`basename $0`
usage()
{
	echo "Usage: $CMD [-sb] [-t timeout] cmd args"
	echo "-s: Use ssh"
	echo "-b: Background"
	echo "-t: command timeout"
	exit 1
}

set -- `getopt bst:h $*`
if [ $? != 0 ]
then
	usage
fi

if [ -z "$RSH_CLIENT" ]
then
	if test -x /usr/bin/remsh
	then
		RSH_CLIENT=/usr/bin/remsh
	else
		RSH_CLIENT=rsh
	fi
fi


if fping -t 100 localhost >/dev/null 2>&1
then
	PING="fping -q -t 100"
else
	PING="ping -c 1 -w 2"
fi

BACKGROUND=false

for i in $*
do
	case $i in
	-b) BACKGROUND=:; shift;;
	-s) RSH_CLIENT="ssh"; shift;;
	-t) TIMEOUT=$2; shift; shift;;
	-h) usage; shift;;
	--) shift; break;;
	esac
done



for f in $HOSTS
do
	if [ "$f" != "$HOSTNAME" ]
	then
		echo "####################    " $f 1>&2
		$PING $f >/dev/null 2>&1 &&\
		(
			if [ $TIMEOUT -gt 0 ]
			then
				set -m
				$RSH_CLIENT -n $f $* &
				JOB=$!
				sh -c "sleep $TIMEOUT; kill $JOB" &
				WJOB=$!

				wait %1
				kill %2 > /dev/null 2>&1
			else
				if $BACKGROUND
				then
					$RSH_CLIENT -n $f $* &
				else
					$RSH_CLIENT -n $f $*
				fi
			fi
		)||(
			echo $f: dead 1>&2
		)
	else
		echo "####################    " $f "(localhost)" 1>&2
		if $BACKGROUND
		then
			sh -c "$*" &
		else
			sh -c "$*"
		fi
	fi
done
