#!/bin/sh
#
# Using a hosts file as one might find in bitsy:hosts/hosts.campus
# go out over the network and check out each host and what its running.
#
# Uses both ping, and nslookup
#
# 91-10-16 By Shawn Mckay (shawn@eddie.mit.edu)
#

echo ""
echo "Survey V1.0"
echo "Mail bugs/comments to shawn@eddie.mit.edu"
echo ""
echo "Starting time: `date`"

#
# Specify target network
#

TARGET=18.62

echo "Compuing active usage on $TARGET subnet ..."

echo ""
echo "Hostname                  Inet-Addr   Status      O/S        Cpu"

#
# Ok, now check out each host, get address and
#     derive the remaining info by hand.
#

NALIVE=0
NDEAD=0

#
# Make sure have database
#

if [ ! -f hosts.campus ]
then
	echo "Sorry, no hosts.campus database file located in this directory."
	exit 1
fi

#
# Ok, run it
#

for addr in `cat hosts.campus | grep -v '^#' | grep $TARGET | cut -f1`
do

	#
	# Lookup who we are talking about
	# Hey, lets ask the name service ":-)"
	#

	NAME=`hostinfo -h $addr`
	NERR=`echo $NAME | grep ':' | wc -l`
	NERR=`expr $NERR`

	if [ $NERR = 1 ]
	then
		NAME="UNKNOWN"
	fi

	#
	# Ok, do a ping, 1x 1k packet
	#

	RET_PING=`ping $addr 1024 1 | wc -l`
	
	if [ $RET_PING = 6 ]
	then
		STATUS="OK"
		NALIVE=`expr $NALIVE + 1`
	else
		STATUS="DEAD"
		NDEAD=`expr $NDEAD + 1`
	fi

	#
	# OK, Lookup OS and CPU type from name server
	#
	# Its REALLY gross I have to do it this way, but
	# nothing else on the system is smart enough to do
	# an HINFO query. And nslookup has no easy option for
	# this query from the command line.
	#

	echo "set type=HINFO" > tx$$
	echo "$NAME" >> tx$$

	T=`nslookup < tx$$ | grep CPU`
	/bin/rm -f tx$$

	OS=`echo $T | cut -d' ' -f3 | cut -c4-`
	CPU=`echo $T | cut -d' ' -f2 | cut -c5-` 

	#
	# Announce what stats we have derived,
	# to keep things unform, this is last thing done.
	#
	# I should NOT have to use this gross hack "(padit)", but oh well.
	# It was faster to do this then to play with the shell enough to
	# force the point.
	#

	echo -n "`./padit 20 $NAME`      $addr     `./padit 5 $STATUS`"
	echo "     `./padit 10 $OS` `./padit 25 $CPU`"
done

#
# Ok, all done, record finish date + time
#

echo ""
echo "Finished at: `date`"
echo "Grand total of `expr $NALIVE + $NDEAD`, $NALIVE OK, $NDEAD DEAD."
