#!/bin/bash

storage_name=""
storage_dir=""
time_out=5
available_after_hour=3
rclone_conf="/root/.config/rclone/rclone.conf"

[ -r /etc/check_mk/rclone_s3_logs.cfg ] && . /etc/check_mk/rclone_s3_logs.cfg

if [ -z $storage_name -o -z $storage_dir ] ; then
	exit
fi

which rclone &>/dev/null
if [ ! $? -eq 0 ] ; then
	exit
fi

if [ ! -f $rclone_conf  ] ; then
	exit
fi

if [ $(grep $storage_name $rclone_conf | wc -l) -eq 0 ]; then
	exit
fi

out="$(timeout ${time_out} rclone ls ${storage_name}:${storage_dir} 2>/dev/null)"

yesterday=$(date '+%Y%m%d' -d "yesterday")
today=$(date '+%Y%m%d')
current_hour=$(($(date '+%H')))

msg=""

if [ $(echo "$out" | grep $yesterday | wc -l) -eq 0 ]; then
	msg="log ${yesterday} not uploaded, ${msg}"
fi

if [ $current_hour -ge $available_after_hour -a $(echo "$out" | grep $today | wc -l) -eq 0 ]; then
	msg="log ${today} not uploaded, ${msg}"
fi

if [ -z "$msg" ]; then
	echo "0 rclone_s3_logs - OK"
else
	echo "2 rclone_s3_logs - CRITICAL $msg"
fi
