#/bin/bash

PROGNAME=$(basename $0)
ERR_MESG=()
LOGGER="`which logger` -i -p kern.warn -t"

STATE_OK="0"
STATE_CRITICAL="2"

FSTAB=/etc/fstab
MTAB=/proc/mounts

TIME_TILL_STALE=3

function log() {
        $LOGGER ${PROGNAME} "$@";
}

UUIDs=`xe sr-list type=nfs params=uuid | grep -v '^$' | awk '{print $5}'`

for UUID in ${UUIDs} ; do

	## check if exist in /proc/mounts
	grep $UUID $MTAB &>/dev/null
	RET=$?
	if ! [ $RET = 0 ];then
		log "CRIT: UUID $UUID is not mounted."
		ERR_MESG[${#ERR_MESG[*]}]="Could not find UUID ${UUID} in $MTAB file."
	else
		MP=`grep $UUID $MTAB`
	fi

        ## check if it stales
        df -k ${MP} &>/dev/null &
        DFPID=$!
        for (( i=1 ; i<$TIME_TILL_STALE ; i++ )) ; do
                if ps -p $DFPID > /dev/null ; then
                        sleep 1
                else
                        break
                fi
        done
        if ps -p $DFPID > /dev/null ; then
                $(kill -s SIGTERM $DFPID &>/dev/null)
                ERR_MESG[${#ERR_MESG[*]}]="${MP} did not respond in $TIME_TILL_STALE sec. Seems to be stale."
        else
        ## if it not stales, check if we can write to it
		MOUNT=`echo $MP | awk '{print $2}'`
		TOUCHFILE="$MOUNT/testfile"
                touch $TOUCHFILE &>/dev/null &
                TOUCHPID=$!
                for (( i=1 ; i<$TIME_TILL_STALE ; i++ )) ; do
                        if ps -p $TOUCHPID > /dev/null ; then
                                sleep 1
                        else
                                break
                        fi
                done
                if ps -p $TOUCHPID > /dev/null ; then
                        $(kill -s SIGTERM $TOUCHPID &>/dev/null)
                        log "CRIT: ${TOUCHFILE} is not writable."
                        ERR_MESG[${#ERR_MESG[*]}]="Could not write in ${MP} in $TIME_TILL_STALE sec. Seems to be stale."
                else
                        rm ${TOUCHFILE} &>/dev/null
                fi
        fi
done

if [ ${#ERR_MESG[*]} -ne 0 ]; then
        echo -n "CRITICAL: "
        for element in "${ERR_MESG[@]}"; do
                echo -n ${element}" ; "
        done
        echo
        exit $STATE_CRITICAL
fi

echo "NFS OK: All storage mounts are up and writeable"
exit $STATE_OK
