#!/bin/csh -f

if ("$1" == "-v") set VERBOSE
if ("$1" == "-V") then
	set VERBOSE
	set DEBUG
endif

if (-e /vmunix) then
	set PING = /usr/etc/ping
else
	set SOLARIS

	set PING = /usr/sbin/ping
endif

if (-e /usr/local/bin/timeout) then
	set TIMEOUT = "/usr/local/bin/timeout 10"
else
	set TIMEOUT
endif


set HOSTNAME = `hostname`
set DOMAIN = `domainname`
if ($?VERBOSE) echo "#" $HOSTNAME is in $DOMAIN

if ($?VERBOSE) echo "#	" getting ypmaster info for $DOMAIN
set YPMASTER = `ypwhich -m passwd`
if ($?VERBOSE) echo "#" ypmaster for $DOMAIN is $YPMASTER

if ($?VERBOSE) echo "#	" getting ypserver info
ypcat -k ypservers | sed 's; .*;;' > /tmp/ypservers.$DOMAIN.$$

set FAILED = 0
if ($?VERBOSE) echo "#	" getting ypclients info from $YPMASTER
if ($HOSTNAME == $YPMASTER) then
	cat /etc/ypclients | tr A-Z a-z | egrep -v "#|\-fddi" | sort -u > /tmp/ypclients.$DOMAIN.$$
else
	rsh $YPMASTER cat /etc/ypclients |& tr A-Z a-z | egrep -v "#|\-fddi" | sort -u > /tmp/ypclients.$DOMAIN.$$
	if ($status) then
		set FAILED = 1
		if ($?VERBOSE) echo "#" rsh to $YPMASTER failed
	endif
endif

if ($FAILED) then
	foreach HOST ( `cat /tmp/ypservers.$DOMAIN.$$` )
		if ($HOST != $YPMASTER) then
			if ($?VERBOSE) echo "#	" getting ypclients info from $HOST
			if ($HOSTNAME == $HOST) then
				cat /etc/ypclients | tr A-Z a-z | egrep -v "#|\-fddi" | sort -u > /tmp/ypclients.$DOMAIN.$$
				set FAILED=0
			else
				rsh $HOST cat /etc/ypclients |& tr A-Z a-z | egrep -v "#|]\-fddi" | sort -u > /tmp/ypclients.$DOMAIN.$$
				if ($status) then
					if ($?VERBOSE) echo "#" rsh to $HOST failed
				else
					set FAILED=0
					break
				endif
			endif
		endif
	end
	if ($FAILED) then
		echo "#" could not get ypclient info
		exec /bin/rm /tmp/*.$$
	endif
endif

if ($?VERBOSE) echo "#	" getting domain info for ypclients
foreach HOST ( `cat /tmp/ypclients.$DOMAIN.$$` )
	if ($?VERBOSE) echo -n "# $HOST "
	$PING $HOST 5 > /dev/null
	if ($status) then
		if ($?VERBOSE) echo does not respond
	else
		if ($HOST == $HOSTNAME) then	
			domainname >& /tmp/domainname.$$
		else
			$TIMEOUT rsh $HOST domainname >& /tmp/domainname.$$
		endif
		set STATUS = $status
#		echo ">" $HOST $STATUS
		if (`cat /tmp/domainname.$$ | wc -l` <= 1) then
			set RDOM = `cat /tmp/domainname.$$`
		else
			set RDOM = "=== VERBOSE ==="
		endif
		if ( ( ! $STATUS ) \
		    && "$RDOM" == "$DOMAIN" ) then
			if ($?VERBOSE) echo is in $DOMAIN
			echo $HOST
		else
			if ( $STATUS == 60 ) set RDOM = "Timed out."
#			if ( $STATUS ) then
#				echo is NOT in $DOMAIN \( status=$STATUS \)
#			else
				if ($?VERBOSE) echo is NOT in $DOMAIN \( $RDOM \)
				if ( ( $?DEBUG ) \
				    && "$RDOM" == "=== VERBOSE ===" ) then
					cat /tmp/domainname.$$ | sed 's;\(.\);#	\1;'
				endif
#			endif
		endif
	endif
end

/bin/rm /tmp/*.$$
