#!/bin/tcsh
# Generate summaries of system health from portal stdout log. 

if ($#argv != 1) then
  echo Must specify portal log file.
  echo usage: `basename $0` portalLogFile
  exit 1
endif


set portalLog=$1

set awkdir=$SIAM_HOME/shoreUtils

echo "<title>Node status summary</title>" 
echo "<body><pre>" 

# Determine last ppp link with mooring
awk -f $awkdir/lastConnection.awk /var/log/messages
echo 

foreach node ('mse surface 1446' 'node421 secondary 1481' 'node410 snubber 1482' 'node401 shelf 1520')

  set nodeName=`echo $node | cut -d ' ' -f 1`
  set aliasName=`echo $node | cut -d ' ' -f 2`
  set nodeID=`echo $node | cut -d ' ' -f 3`

  # Plot JVM memory
  awk -f $awkdir/meminfo.awk $nodeID $portalLog > meminfo
  awk '{print $1 " " $2}' meminfo > totalMem
  awk '{print $1 " " $4}' meminfo > usedMem

  set memGraph=${nodeName}-mem.gif
  graph -T gif --title-font-size 0.05 -L "${nodeName}: Total (red) and used (green) JVM memory" -X "elapsed hrs" -Y "MBytes" -C totalMem usedMem > $memGraph

  ### echo "Plot written to $memGraph"
 
  # Plot JVM threads
  awk -f $awkdir/threads.awk $nodeID $portalLog > threads

  set threadGraph=${nodeName}-threads.gif
  graph -T gif --title-font-size 0.05 -L "${nodeName}: JVM threads" -X "elapsed hrs" -Y "#threads" -y 15 80 -C threads > $threadGraph

  ### echo "Plot written to $threadGraph"

  echo -n "<b>${nodeName}, aka '$aliasName' (ID $nodeID): </b>" 
  echo "" 
  awk -f $awkdir/listPorts.awk $nodeID $portalLog 

  # Summarize wakeup/comms success
  echo "" 
  awk -f $awkdir/wakeup.awk $nodeName $portalLog 

  # Summarize sleep statistics
  ### echo "" 
  ### echo -n "$nodeName sleep stats: " 
  ### awk -f $awkdir/sleepStats.awk $nodeID $portalLog | tail -1 

  # Summarize each data stream for this node
  echo "\nDevice stream ages as received at portal, at " `date` ":"
  if (-e $SIAM_HOME/logs/$nodeID) then 
###     echo "$SIAM_HOME/logs/$nodeID exists?"
    foreach file ($SIAM_HOME/logs/$nodeID/*.dat) 
      set totalBytes=`ls -l $file | awk '{print $5}'`
      set deviceID=`echo $file:r:t | cut -d _ -f 1`

      logView -utc $deviceID $SIAM_HOME/logs/$nodeID | awk -f $awkdir/streamAge.awk 
    end
  endif

  # Plot clock offsets
  set sysclkOffsets=${nodeName}-sysclkOffsets
  awk -f $awkdir/ntpOffset.awk $nodeName $portalLog > $sysclkOffsets

  set ricohOffsets=${nodeName}-ricohOffsets
  awk -f $awkdir/ricohOffset.awk $nodeName $portalLog > $ricohOffsets


  set offsetGraph=${nodeName}-offset.gif

  graph -T gif --title-font-size 0.05 -L "${nodeName}: Sysclk (red) and Ricoh (green) NTP offsets" -X "elapsed hrs" -Y "NTP offset sec" -C $sysclkOffsets $ricohOffsets > $offsetGraph
  ### echo "Plot written to $offsetGraph"

  echo '<IMG SRC='\"$offsetGraph\"'>' 
  echo '<IMG SRC='\"$memGraph\"'>' 
  echo '<IMG SRC='\"$threadGraph\"'>' 

  echo "<HR>" 
end
echo "</pre></body>" 
echo "Done"
exit 0

