#!/bin/sh
set -u
if [ "${1:-}" = "-x" ] ; then set -xv; shift; fi

check_pnfs() {

   pnfson=$1

   correct_MR="program 100005 version 1 ready and waiting"
   correct_NR="program 100003 version 2 ready and waiting"
   complain=6
   CF=$TEMP_DIR/pnfs_down
   CF_current() { if [ ! -r $CF ]; then CF_set 0 ; fi;  cat $CF; }
   CF_set() { rm -fr $CF; echo $1 > $CF ; }
   current=`CF_current`
   D=`date "+%Y-%m-%d-%H:%M:%S"`

   #If the following:
   # 100005 1: refers to mountd program running NFS version 1
   # 100003 2: refers to nfs program (PNFS in our case) running NFS version 2.
   MR=`$loc/rpcinfo -u $pnfson 100005 1 2>&1`
   NR=`$loc/rpcinfo -u $pnfson 100003 2 2>&1`

   msg1="$D $pnfson  MOUNTD: $MR    NFSD: $NR"

   if [ "$correct_MR" != "$MR" -o "$correct_NR" != "$NR" ]; then
        current=`expr $current + 1`
        if [ $current -gt $complain ]; then 
          rc=1
          msg2="PROBLEM WITH PNFS ON $pnfson"
          enstore alarm --raise --severity "A" --root-error "$msg1  $msg2"
          enstore sched --override enstore --saagStatus red
	  if [ `uname` == "Linux" ]; then
              /usr/bin/Mail -s "$msg1 $msg2" $ENSTORE_MAIL
	  else
              temp_file=$TEMP_DIR/checkpnfs_mail
              echo "Subject: $msg1 $msg2" > $temp_file
	      echo "$msg1 $msg2" >> $temp_file
	      /usr/bin/mail $ENSTORE_MAIL < $temp_file
	      rm -f $temp_file
	  fi
          current=0
       fi
       rc=0
   else
        echo $msg1   # where ever it is running
	current=0
        rc=0
   fi

   CF_set $current
   return $rc
}



#If we don't have ENSTORE_MAIL, get it from the config server.
if [ -z "$ENSTORE_MAIL" ]; then
   $ENSTORE_MAIL=`enstore conf --show crons email`
fi

TEMP_DIR=/tmp

case `uname` in
        IRIX*)  loc=/usr/etc
                fstab=/etc/fstab
                ;;
        Linux*) loc=/usr/sbin
                fstab=/etc/fstab
                ;;
        SunOS*) loc=/usr/sbin
                fstab=/etc/fstab
                ;;
        *)      loc=/usr/sbin
                fstab=/etc/fstab
                echo "UNKNOWN OS - FIX ME"
                exit 1
esac


#grep through the /etc/mtab file looking for pnfs entries.  pnfs_list will
# contain just the hostnames of pnfs servers.
pnfs_list=`grep pnfs $fstab | egrep -v "^#" | awk '{print $1}' | sed 's/:.*$//' | sort | uniq`

echo pnfs_list $pnfs_list

rc=0
for pnfson in $pnfs_list; do
    check_pnfs $pnfson
    rc=$rc || $?
done

exit $rc
