#!/bin/sh

# A utility to take a log file and a DSA name, and
# produce a graph of the resulting uptime.

# Syntax: stat_graph <DSA name> <log file> [Network]
#
# DSA name   can be any substring of the DSA that is unique to the log.
# log_file   Name of the log to be processed.
# Network    Optional arument. Some substring that is unique to the
#			       network address you want.
#
# This syntax is a little bit unfriendly, and could
# be improved a little bit for the naive users.

# Requires X-Graph at the moment.

if [ $# -lt 2 ]
then
	echo "Usage: stat_graph <DSA name> <log file> [Network]"
	echo "Insufficient Arguments. Exit."
	exit 
fi 

DSA_name="$1"
log_file="$2"

if [ ! -f "$log_file" ]
then
	log_file="$log_file"_log
fi

if [ ! -f "$log_file" ]
then
	echo "Can't find log file $log_file. Exit."
	exit
fi

trap "rm -f /tmp/st_gr0_$$ /tmp/st_gr1_$$ /tmp/st_gr2_$$ ;exit" 0 2 15	# clean up if we die

grep -i "$DSA_name" "$log_file" > /tmp/st_gr0_$$

if [ $# -eq 3 ]
then 
	Network="$3"
	
	if [ `echo "$Network" | grep -c -i "X25"` -eq 1 ]
	then
		Network="TELEX+00728722+X.25(80)+01+"
	fi
	if [ `echo "$Network" | grep -c -i "janet"` -eq 1 ]
	then
		Network="TELEX+00728722+X.25(80)+02+"
	fi
	if [ `echo "$Network" | grep -c -i "internet"` -eq 1 ]
	then
		Network="TELEX+00728722+RFC-1006+03+"
	fi
	if [ `echo "$Network" | grep -c -i "local"` -eq 1 ]
	then
		Network="TELEX+00728722+RFC-1006+04+"
	fi
	if [ `echo "$Network" | grep -c -i "IXI"` -eq 1 ]
	then
		Network="TELEX+00728722+X.25(80)+06+"
	fi
	if [ `echo "$Network" | grep -c -i "x121"` -eq 1 ]
	then
		Network="X121"
	fi
	if [ `echo "$Network" | grep -c -i "ns"` -eq 1 ]
	then
		Network="NS"
	fi

	fgrep "$Network" /tmp/st_gr0_$$ > /tmp/st_gr1_$$
	mv /tmp/st_gr1_$$ /tmp/st_gr0_$$
fi

cat /tmp/st_gr0_$$ | awk "-F#" 'NF==5 {print $5}' | sort -u > /tmp/st_gr1_$$

count=1
cat /tmp/st_gr1_$$ | while read i
do
	echo "0 0" >> /tmp/st_gr2_$$
	echo "0 100" >> /tmp/st_gr2_$$

	fgrep "$i" /tmp/st_gr0_$$ | \
	awk "-F#" 'NF==5 { if ($2 == 1) 
				{
				  printf("%d %d\n", NR, 100-'$count') 
				}
				else 
				{
				  printf("%d %d\n", NR, '$count')
				}
			  }' >> /tmp/st_gr2_$$
	echo $i | awk  '
			/\TELEX+00728722+X.25(80)+01\+/ { print "\"Int X-25\n" }
			/\TELEX+00728722+X.25(80)+02\+/ { printf("\"Janet\n")}
			/\TELEX+00728722+RFC-1006+03\+/ { printf("\"Internet\n")}
			/\TELEX+00728722+RFC-1006+04\+/ { printf("\"Local Ether\n")}
			/\TELEX+00728722+X.25(80)+06\+/ { printf("\"IXI\n")}
			/IXI/ { printf("\"IXI\n")}
			/X121/ { printf("\"X121\n")}
			/NS/ { printf("\"Network Service\n")}
			/dsa-available/ { printf("\"DSA Available\n")}
		       ' >> /tmp/st_gr2_$$
	count=`expr $count + 1`
	echo >> /tmp/st_gr2_$$
done
cat /tmp/st_gr2_$$ | xgraph -x Time -y Availability \
			    -t "$DSA_name $log_file"



