#!/bin/sh -e

finish() {
	trap '' EXIT
	exit $1
}

ok() {
	echo "OK: $@"
	finish 0
}

warning() {
	echo "WARNING: $@"
	finish 1
}

critical() {
	echo "CRITICAL: $@"
	finish 2
}

unknown() {
	echo "UNKNOWN: $@"
	finish 3
}

error() {
	unknown "unknown error while running check"
}

trap error EXIT

dir="$1"

[ -d "$dir/rdiff-backup-data" ] || \
	critical "directory $dir/ doesn't contain rdiff-backup-data"

files=`find "$dir/rdiff-backup-data/" -maxdepth 1 -mmin -1500 -name 'file_statistics.*'`
if [ "$files" ]; then
	nl=`echo -e "$files" | wc -l`
else
	nl=0
fi

if [ $nl -ge 1 ]; then
	if [ -f "$dir/rdiff-backup-data/backup.log" ]; then
		lognl=`wc -l "$dir/rdiff-backup-data/backup.log" | cut -d' ' -f1`
	else
		lognl=0
	fi
	if [ $lognl -eq 0 ]; then
		file=`echo -e "$files" | head -n1`
		date=`stat -c'%y' "$file" | cut -d'.' -f1`
		ok "last backup made on $date - $nl in the last 25 hours"
	else
		warning "backup.log may contains errors, check and empty file if needed"
	fi
else
	critical "no file_statistics in the last 25 hours"
fi

unknown "finished without hitting state"
