#!/bin/sh
#
# Taken from http://www.sentric.ch/blog/how-to-monitor-hbase-health-by-nagios
#
# Description:
# This plugin will return information about the status of HBASE

# -- adellam:
# Run the script as hbase
#
user=$1
hbaseBin=/usr/bin/hbase
hbaseCmd="sudo -u $user -i $hbaseBin"
problemStrings="inconsistent|corrupt|failed|exception"
if [ ! -x $hbaseBin ]; then
    echo "ERROR: cannot execute $hbaseBin"
    exit 2
fi
tmpFile=$(tempfile --suffix '_hbck_out')
if [ ! -f "$tmpFile" ]; then
    echo "Problem creating a tempfile for hbck output..." 1>&2
    exit 1
fi
$hbaseCmd hbck > $tmpFile
if [ ! $? -eq 0 ]; then
    echo "Error while executing $hbaseCmd hbck"
    exit 2
fi
count=$(grep -Ei -c "$problemStrings" $tmpFile)
if [ $count -eq 0 ]; then
    message="Ok. HBase is healthy."
    exit_code=0
else
    error=$(grep -Ei "$problemStrings" $tmpFile)
    message="ERROR: $error"
    exit_code=2
fi
hbckDetails=$(head -n 17 $tmpFile && tail -n 2 $tmpFile)
if [ -f "$tmpFile" ]; then
    rm -f $tmpFile
fi
echo "$message | $hbckDetails"
exit $exit_code
