
#!/bin/ksh
# W. Roelofs
# Collect filer uptime (ping) 
# Version 1.0 14-5-2007 
#set -x
PATH=$PATH:/usr/sbin:/usr/bin; export PATH
#
FILER=$1
if [ "$FILER" = "" ]; then echo "Provide filer hostname: $0 <filer hostname>"; exit; fi 

RUN_INTERVAL=60 # seconds
DAYLOG=/volumes/v1/home/nldsm01/scripts/data/uptime_${FILER}_daily.log  
TMP=/volumes/v1/home/nldsm01/scripts/data/uptime_${FILER}_min.log$$
OLDTMP=/volumes/v1/home/nldsm01/scripts/data/uptime_${FILER}_min.log
PIDFILE=/volumes/v1/home/nldsm01/scripts/etc/uptime_${FILER}_PID

TODAY=`date +%Y-%m-%d`   
NEXTDATE=$TODAY

# check if there is previous script running, and if so exit.
PID=`cat ${PIDFILE}`
ps -p $PID > /dev/null 2>&1
if [ $? -eq 0 ]; then exit; fi 

function collect_kpi {
 # collect kpi data $1 input datafile, $2 date, $3 filer hostname, $4 output datafile 
 noping=`grep xdown $1 |wc -l`
 total=`cat $1 |wc -l`
 perc_up="no data"

 # some ifs  to prevent division by zero
 if [ $noping -gt 0 -a $total -gt 0 ]; then
   perc_up=`echo "scale=2; 100-(100/($total/$noping))"|bc`
 else
   if [ $noping -eq 0 -a $total -gt 0 ]; then perc_up=100; fi
 fi
 echo "$3,$2,$perc_up" >> $4
}

# check if there exists a min_log from a previous aborted session
# and process results
if [ -f ${OLDTMP}${PID} ]; then
  # Get date in old file
  LN=`head -n 1 ${OLDTMP}${PID}`
  DAT=`echo $LN | cut -d, -f2` 
  DAT=`echo $DAT | cut -d@ -f1` 
  # If it equals present day than copy contents to ${TMP}
    if [ "$DAT" = "$TODAY" ]; then 
      cat ${OLDTMP}${PID} >> ${TMP} 
      rm -f ${OLDTMP}${PID}
    else
      collect_kpi "${OLDTMP}${PID}" "$DAT" "$FILER" "$DAYLOG"   
      rm -f  ${OLDTMP}${PID} > /dev/null 2>&1
    fi
fi

echo $$  > $PIDFILE # save process id of this run 

# main loop ends when day changes
while [ "$NEXTDATE" = "$TODAY" ];  
do 
  /usr/sbin/ping ${FILER}
  stat=$?
  if [ $stat -eq 0 ]; then stat=xup; else stat=xdown; fi
  echo "${FILER},`date +%Y-%m-%d@%H:%M`,$stat" >> ${TMP}
  sleep $RUN_INTERVAL 
  NEXTDATE=`date +%Y-%m-%d`
done

collect_kpi "$TMP" "$TODAY" "$FILER" "$DAYLOG"
 
rm -f ${TMP} > /dev/null 2>&1
echo > ${PIDFILE}

