#!/bin/bash
#
# Usage: reach-count <reachlist file> [retries]
# Returns: ascii value of number of hosts reachable 
#          from list contained in <reachlist file>.
#
# Copyright (C) 1998, 1999 Philip J. Lewis
#
#    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 2 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., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#    Contact: lewispj@email.com
#

INSTALL=/usr/local/bin
PATH=$PATH":$INSTALL"
NULL="/dev/null"

old_is_alive()
{
	# expire any arp cache entries first
	arp -d $1 >$NULL 2>$NULL
	ping -c 2 -n -l1 $1 -i1 >$NULL 2>$NULL &

	PINGPID=$!
	# wait 1 seconds then kill ping process
        sleep 1
        kill -9 $PINGPID >$NULL 2>$NULL

	# Return 0 for failure (ie. could kill ping), 1 for alive
	if [ $? = 0 ]; then
		echo 0
		return 0
	else
		echo 1
		return 1
	fi
}

is_alive()
{
	# expire any arp cache entries first
	arp -d $1 >$NULL 2>$NULL
	ping -c 2 -n -l1 $1 -i1 >$NULL 2>$NULL
	# Return 0 for failure (ie. could kill ping), 1 for alive
	if [ $? = 1 ]; then
		echo 0
		return 0
	else
		echo 1
		return 1
	fi
}

REACHLIST=$1
RETRIES=$2

if [ "$RETRIES" = "" ]; then
	RETRIES=1
fi

(
REACHCOUNT=0
read
while [ "$REPLY" != "" ]; do
	#echo pinging $REPLY
	if [ "$(is_alive $REPLY)" = "1" ]; then
		REACHCOUNT=`expr $REACHCOUNT + 1`
	fi
	read
done
echo $REACHCOUNT
) < $REACHLIST

exit 0
