#!/usr/bin/openrc-run

description="Waiting for local DNS resolver"

. /opt/etc/functions.openrc

# /etc/conf.d/wbwait variables:
# DNS_GOOD_FQDN - FQDN to resolve

DNS_GOOD_FQDN=${DNS_GOOD_FQDN-"google.com"}
DNS_TIMEOUT=${DNS_TIMEOUT-"30"}

HOST=`which host`

depend()
{
	need net
	provide ${SVCNAME} dns
}

wait_for_resolver()
{
	local _rv=1 _count=${DNS_TIMEOUT}
	while [ ${_count} -gt 0 ]; do
		# BUGBUG: DNS_GOOD_FQDN should be good, 'host' returns 0 for bad ones
		host -4 -R 1 -t A ${DNS_GOOD_FQDN} > /dev/null 2>&1 && break
		_count=$((${_count}-1))
		ewarn "${ME}: waiting for resolver, ${_count} more tries..."
		sleep 1
	done
	[ ${_count} -gt 0 ]
}

start()
{
	local _rv
	ebegin "Starting \"${SVCNAME}\""
	if ! [ -x "$HOST" ]; then
		update_me
		eerror "${ME}: \"host\" not found, install \"bind-tools\" or whatever."
		eend 1
		return 1
	fi
	wait_for_resolver
	_rv=$?
	eend ${_rv}
	return ${_rv}
}

stop()
{
	ebegin "Stopping \"${SVCNAME}\""
	eend 0
	return 0
}
