# Checks DNS and restarts kresd if necessary

# check prerequisites

. /lib/functions.sh

if [ ! -x "$(command -v host)" ]; then
	echo 'dnscheck error: host is not installed, exiting' >&2
	exit 1
fi

perform_check() {

    local host
    local server
    local timeout
    local maxfailures
    local failure=0

    config_get host check_service host "CHANGEME"
    config_get server check_service server "10.64.0.1"
    config_get timeout check_service timeout "5"
    config_get maxfailures check_service maxfailures "3"

    # check DNS
    host -w "${timeout}" "${host}" "${server}" &> /dev/null
    if [ $? -ne 0 ]; then
        failure=1
        logger -p err -t "dnscheck" "kresd failed to respond, ${failcount} of ${maxfailures}"
        let "failcount++"
    else
        if [ $failcount -ge 0 ]; then
            logger -p info -t "dnscheck" "kresd is responding again"
        fi

        failcount=0
    fi

    if [ $failcount -ge $maxfailures ]; then
        failcount=0
        logger -p err -t "dnscheck" "kresd not responding, restarting"

        # restart service
        /etc/init.d/resolver restart
    fi

    return $failure
}


# read configuration
config_load dnscheck

# check loop
logger -p info -t "dnscheck" "Starting kresd monitoring"
failcount=0
while sleep 10; do
    perform_check ${job}
    if [ $? -ne 0 ]; then
        logger -p err -t "dnscheck" "kresd did not respond and was restarted"
    fi
done

exit 0