#!/bin/bash

now="$(date +%s)"

resolved="$(dig +short kunbox.net)"

if [[ -n "$resolved" ]]
then
    echo "$now" > /var/tmp/unbound_last_resolved
    exit 0
fi

last_resolved="$(cat /var/tmp/unbound_last_resolved)"
five_min_ago="$(expr $now - 300)"

if [[ "$last_resolved" -lt "$five_min_ago" ]]
then
    systemctl restart unbound

    # Write "in 25 minutes" timestamp to /var/tmp/unbound_last_resolved.
    # If resolving gets fixed by the restart, this will get re-written
    # on the next run of this script. If not, this script will restart
    # unbound again in half an hour (25min plus 5min grace time).
    echo "$(expr $now + 1500)" > /var/tmp/unbound_last_resolved
fi