#!/bin/bash

statusdata_path="/var/cache/icinga2/status.dat"
objectscache_path="/var/cache/icinga2/objects.cache"

if [ ! -f $statusdata_path ];
then
    sudo icinga2 feature enable statusdata 1> /dev/null
    sudo service icinga2 restart 1> /dev/null

    n=0
    while [ $n -lt 3 ]
    do
        sleep 15

        if [ -f $statusdata_path ];
        then
            break
        fi

        n=$(( $n + 1))
    done

    if [ $n -eq 3 ];
    then
        echo "[FAIL] Icinga2 status.dat not found ($statusdata_path)"
        exit 1
    fi
fi

echo "[OK] Icinga2 status.dat found ($statusdata_path)"

if [ -f $objectscache_path ];
then
    echo "[OK] Icinga2 objects.cache found ($objectscache_path)"
else
    echo "[FAIL] Icinga2 objects.cache not found ($objectscache_path)"
    exit 1
fi

status_time=$(stat --format="%Y" $statusdata_path)

now=$(date +"%s")
sleep $(((15 + 5) - ($now - $status_time)))

new_status_time=$(stat --format="%Y" $statusdata_path)

if [ $new_status_time -eq $status_time ];
then
    echo "[FAIL] Icinga2 status.dat is not being updated (Last update: $(date -r $statusdata_path '+%x %X'))"
    exit 1
else
    echo "[OK] Icinga2 status.dat is being updated (Last update: $(date -r $statusdata_path '+%x %X'))"
fi
