#!/bin/sh
set -u  # force better programming and ability to use check for not set

if [ "${1:-}" = "-x" ] ; then set -xv; shift; fi

# $Id$

job=${1:-"route"}

if [ -x /usr/local/bin/netperf ]; then
   netperf=/usr/local/bin/netperf
elif [ -x /usr/bin/netperf ]; then
   netperf=/usr/bin/netperf
elif [ -x /opt/netperf/netperf ]; then
   netperf=/opt/netperf/netperf
else
   echo routes - where is netperf\?
fi

host=`hostname -s`
gang=`gang`

# function to convert mover id to corresponding node name
moverToNode() { enstore config --show $1 |
		awk -F: '/\<data_ip\>/ {match($2, ".*((d0|stk|cdf)enmvr[1-9][0-9]*(a|b)).*", a); print a[1]}'
	      }

# function to list known down movers
lsKnownDown() { enstore sched --show |
		awk '/Enstore Items/		  {known=0}
		     /Enstore Items Known Down/   {known=1}
		     /[A-Z0-9_]*\.mover/ && known {print $1}' |
		while read mover
		do
		  moverToNode $mover
		done
	      }

# function to select critical nodes (servers *srv[0-24], mainly)
#	fndca3a		dcache head node (fndca)
#	stkendca2a	dcache door node (fndca1)
criticalNode() { echo "$1" |
		 egrep '(d0|stk|cdf)ensrv[0-24]|fndca3a|stkendca2a' > /dev/null
	       }

case $job in

################################################################################
quickcheck)
    # skip the host node, as well as known down nodes
    omit="$host ssasrv1 $(lsKnownDown)"

    # test peer hosts (they are testing us, too)
    for g in d0en stken cdfen; do
	if [ $g != $gang ]; then
	   peers="${peers:-}`echo $host | sed s/$gang/$g/`\n"
	fi
    done

    # test srv4 nodes on the control network from stkensrv3
    [ $gang = stken ] && peers="${peers}d0ensrv4p\nstkensrv4p\ncdfensrv4p\n"

    # test public dcache and data mover nodes from stkensrv3
    [ $gang = stken ] && extra="/usr/local/etc/farmlets/stkendca /usr/local/etc/farmlets/stkendm"

    NODES=`awk -v omit="$omit" -v host="$host" -v peers="$peers" \
	   'BEGIN {split(omit, x); for (i in x) v[x[i]]=i}
	    $1 == host {printf "%s", peers}
	    ! ($1 in v)' /usr/local/etc/farmlets/${gang}-all ${extra:-} `

    black=#000000
    white=#FFFFFF

    red=#FF0000
    blue=#0000FF
    green=#00FF00

    cyan=#00FFFF
    yellow=#FFFF00
    magenta=#FF00FF

    navy=#000080
    teal=#008080
    coral=#FF7F50
    silver=#C0C0C0
    turquoise=#40E0D0

    bgcolor=$white
    text=$navy

    storit="/root/quickcheck.eepro100.html"
    rm -f $storit
    color=$black
    checkat=10
    cat << EOF >> $storit
<html>
<head>
<title>Network Rate Tests</title>
<meta http-equiv="Refresh" content="1800">
</head>
<body bgcolor="$bgcolor" text="$text">
<h1><center>Network Rate Test</center></h1>
<hr>
<h1><center><a href="http://fndcg0.fnal.gov/~netadmin/onsite/mrtg-stuff">Today's MRTG Graphs</a></center></h1>
<hr>
<h1><center><a href="http://fndcg0.fnal.gov/~netadmin/onsite/stats.html">CD DCG Statistics</a></center></h1>
<hr>
<h1>Rate test between various nodes and `uname -n`</h1>
<h1>Begin: <font color="$green">`date`</font></h1>
<p>
<table bgcolor="$silver" nosave >
<tr>
<th align=center><font color="$color">Node</font></th>
<th align=center><font color="$color">In<br>Production</font></th>
<th align=center><font color="$color">Rate<br>10^6 bits/S</font></th>
<th align=center><font color="$color">Less than<br>$checkat<br>10^6 bits/S?</font></th>
<th align=center colspan=10><font color="$color">Previous Rates<br>&lt;- (newest) . . . (oldest) -&gt;</font></th>
</tr>
EOF

    # lookup movers in enstore config to determine production status
    config="/tmp/quickcheck.config"
    enstore conf --show > $config

    for node in $NODES; do
      CF=/tmp/routes_quickcheck_$node
      production=1
      if echo $node | grep enmvr > /dev/null; then
	grep $node $config || production=0
      fi
      if [ $production -ne 0 ]; then
	 color=$blue
	 prod=Yes
      else
	 color=$teal
	 prod=No
      fi
      echo "<tr>" >> $storit
      echo "<td align=center><font color=\"$color\">$node</font></td>" >> $storit
      echo "<td align=center><font color=\"$color\">$prod</font></td>" >> $storit
      if line=`$netperf -H $node -l 1`; then
	rate=`echo $line | awk '{print $NF}'`
      else
	rate=0
      fi
      if [ `echo "$rate" | cut -d. -f1` -lt $checkat ]; then
	 fcolor=$red
	 if [ $production -ne 0 ]; then
	   msg="Node $node has rate $rate. FIX, or disable its mover."
	   if [ -r $CF ]; then current=`cat $CF`; else current=0; fi
	   current=`expr $current + 1`
	   flag="CHECK"
	   complain=3
	   # important servers set the status ball red, causing a page
	   if [ $complain -eq $current ]; then
	     criticalNode $node && enstore sched --override enstore --saagstatus red
	   fi
	   # back off the frequency with which we complain (Fibonacci wise)
	   fminus1=$complain
	   until [ $complain -ge $current ]; do
	     fminus2=$fminus1
	     fminus1=$complain
	     complain=`expr $fminus2 + $fminus1`
	   done
	   if [ $complain -eq $current ]; then
	     enstore alarm --raise --severity 'A' --root_error="$msg"
	     /usr/bin/Mail -s "$msg" $ENSTORE_MAIL << EOF
`date`
$msg
EOF
	   fi
	 else
	   flag="Yes"
	   current=0
	 fi
	 flag2="<-------------- CHECK THIS. Problem is either NIC/NODE/6509."
      else
	 fcolor=$color
	 flag="&nbsp;"
	 current=0
	 flag2=""
      fi
      echo "$current" > $CF
      echo "$node: $rate x 10^6 bits/S $flag2"
      echo "<td align=center><font color=\"$fcolor\">$rate</font></td>" >> $storit
      echo "<td align=center><font color=\"$fcolor\">$flag</font></td>" >> $storit
      if [ -r /rate-$node ]; then
	# make history go right (oldest) to left (newest)
	tail -n 10 /rate-$node | tac | while read line; do
	  r=`echo $line | awk '{print $NF}'`
	  if [ `echo "$r" | cut -d. -f1` -lt $checkat ]; then
	    fcolor=$coral
	  else
	    fcolor=$color
	  fi
	  echo "<td align=center><font color=\"$fcolor\">$r</font></td>" >> $storit
	done
      fi
      echo "</tr>" >> $storit
      echo "`date` $rate" >> /rate-$node 2>/dev/null
    done

cat << EOF >> $storit
</table>
<h1>Done: <font color="$green">`date`</font></h1>
<h1>Expected nominal rate for (idle) Fast Ethernet connections is ~94 x 10^6 bits/S</h1>
</body>
</html>
EOF

    # next line is not good...
    enrcp $storit ${gang}srv2:/fnal/ups/prd/www_pages/enstore
    ;;

################################################################################
test)
# needs work, parts re-written, not tested
    count=${2:-1}
    testTime=${3:-30}

    if [ $gang = "d0en" ];then
      num=`echo $host | sed -e 's/d0enmvr//' -e 's/[ab]//'`
      max=`tail -1 /usr/local/etc/farmlets/d0enmvr | sed -e 's/d0enmvr//' -e 's/[ab]//'`
    elif [ $gang = "stken" ]; then
      num=`echo $host | sed -e 's/stkenmvr//' -e 's/[ab]//'`
      max=`tail -1 /usr/local/etc/farmlets/stkenmvr | sed -e 's/stkenmvr//' -e 's/[ab]//'`
    elif [ $gang = "cdfen" ]; then
      num=`echo $host | sed -e 's/cdfenmvr//' -e 's/[ab]//'`
      max=`tail -1 /usr/local/etc/farmlets/cdfenmvr | sed -e 's/cdfenmvr//' -e 's/[ab]//'`
    fi
    num1=`expr $num + 1`

    if [ `expr $num / 2 \* 2` -eq $num -a $num -lt $max ]; then
      loop=0
      while [ $loop -lt $count ]; do

	o=netperf.${num1}a-${num}a.output
	enrsh ${gang}mvr${num1}a "$netperf -l $testTime -H ${gang}mvr${num}a >> $o 2>&1 </dev/null &" &
	o=netperf.${num1}b-${num}b.output
	enrsh ${gang}mvr${num1}b "$netperf -l $testTime -H ${gang}mvr${num}b >> $o 2>&1 </dev/null &" &
	sleep $testTime
	sleep 3
	#enrsh ${gang}mvr${num1}a '(. /fnal/ups/etc/setups.sh;setup enstore;$ENSTORE_DIR/sbin/ekill -9 $netperf 2>/dev/null) 1>&- 2>&- <&- &' &

	o=netperf.${num}a-${num1}a.output
	$netperf -l $testTime -H ${gang}mvr${num1}a >> $o 2>&1 </dev/null &
	o=netperf.${num}b-${num1}b.output
	$netperf -l $testTime -H ${gang}mvr${num1}b >> $o 2>&1 </dev/null &
	sleep $testTime
	sleep 3
	#$ENSTORE_DIR/sbin/ekill -9 $netperf 2>/dev/null

	loop=`expr $loop + 1`
      done
    fi
    ;;

################################################################################
rate)
    for i in netperf*.output; do
       l=`tail -1 $i`
       r=`echo $l | cut -f5 -d\ `
       p=`echo $i | sed -e 's/netperf.//' -e 's/.output//'`
       echo $p $r
    done
    ;;

################################################################################
ifconfig)
    server=1
    if [ `echo $host | grep -c mvr` -ne 0 ]; then
      server=0
      node0=`echo $host | sed -e 's/[ab]$//'`
    fi

    e=`/sbin/ifconfig eth0`
    f=`echo $e| sed -e 's/ Link .*HWaddr/ HWaddr/' -e 's/inet addr:/ addr /' -e 's/UP.*//'`
    if [ $server -eq 1 ]; then
      echo $host $f
    else
      echo ${node0}a $f
      e=`/sbin/ifconfig eth1`
      if [ `echo $e | grep -c UP` -ne 0 ]; then
	f=`echo $e| sed -e 's/ Link .*HWaddr/ HWaddr/' -e 's/inet addr:/ addr /' -e 's/UP.*//'`
	echo ${node0}b $f
      fi
    fi
    ;;

################################################################################
arp)
    /sbin/arp | awk -v host=$host '/^(d0|stk|cdf)en/ {print host,$1,$3}' | sed -e 's/\.fnal\.gov//'
    ;;

################################################################################
check_ifconfig_arp)
    ifmaster=${2:-ifconfig.master}

    if [ ! -r $ifmaster ]; then
      echo "Can not read file $ifmaster (made by 'rgang -n farmlet \"$0 ifconfig \" > $ifmaster ')"
    fi
    arplist=/tmp/arp.list
    rm -f $arplist
    $0 arp >$arplist

    cat $arplist | while read who node add; do
      master=`grep $node $ifmaster`
      masteradd=`echo $master | cut -f4 -d\ `
      if [ "$masteradd" != "$add" ]; then
	 masternode=`grep $add $ifmaster| cut -f1 -d\ `
	echo Node $who thinks $node points to $add but master says $masteradd \($add is $masternode\)
	fi
    done
    ;;

################################################################################
makearp)
    ifmaster=${2:-ifconfig.master}

    if [ ! -r $ifmaster ]; then
      echo "Can not read file $ifmaster (made by 'rgang -n farmlet \"$0 ifconfig \" > $ifmaster ')"
    fi
    cat $ifmaster | while read node eth x hwaddr junk; do
      echo /sbin/arp -i $eth -s $node $hwaddr
    done
    ;;

################################################################################
route)
    /sbin/route
    ;;

esac
