#!/bin/bash

function ok_exit()
{
	echo "OK"
	exit 0
}

function skip_check()
{

	# no check between 1:00 and 5:59
	HR=`date +'%H'`
	if [ $HR -gt 0 -a $HR -lt 6 ];then
		ok_exit
	fi

	# md raid check
	mds=$(ls /sys/block/ 2>/dev/null | grep -E '^md[0-9]+$' || true)
	for mdraid in $mds; do
		if [ -f "/sys/block/$mdraid/md/sync_action" ]; then
			action=$(<"/sys/block/$mdraid/md/sync_action")
			case "$action" in
				check|repair|resync|recover)
				ok_exit
				break
				;;
			esac
		fi
	done

	# ZFS maintenance
	if (which zpool >/dev/null); then
		if (zpool status | grep -q "\(scrub in progress\|trimming\|resilver in progress\)"); then
			ok_exit
		fi
	fi

	# EXT4 scrub
	if lsblk -o NAME 2>/dev/null | grep -q 'e2scrub'; then
		ok_exit
	fi

}

CORES=`grep -c ^processor /proc/cpuinfo`

CRLOAD=$((CORES+CORES/2))
if [ $CRLOAD -lt 6 ]; then
	CRLOAD=6
fi

LOADS=`cat /proc/loadavg | awk '{print $1 ";" $2}'`
LOAD1=${LOADS%%;*}
LOAD5=${LOADS##*;}

if ! [ ${LOAD1%.*} -lt ${CRLOAD} -o ${LOAD5%.*} -lt ${CRLOAD} ]; then
	skip_check
	echo "${CRLOAD}.00+"
	exit 2
elif ! [ ${LOAD1%.*} -lt ${CORES} -o ${LOAD5%.*} -lt ${CORES} ]; then
	skip_check
	echo "${CORES}.00+"
	exit 1
else
	echo "OK"
	exit 0
fi
