#!/usr/sbin/openrc-run

description="Nameserver information manager."

depend()
{
	need mountall-bootclean.sh
	provide resolvconf
}

[ -x /usr/sbin/resolvconf ] || exit 0

RUN_DIR=/run/resolvconf
ENABLE_UPDATES_FLAGFILE="${RUN_DIR}/enable-updates"
POSTPONED_UPDATE_FLAGFILE="${RUN_DIR}/postponed-update"

log_action_end_msg_and_exit()
{
	eend "$1" ${2:+"$2"}
	return "$1"
}

create_runtime_directories()
{
	umask 022
	if [ ! -d "$RUN_DIR" ]; then
		mkdir "$RUN_DIR" || return 1
	fi
	command -v restorecon >/dev/null && restorecon "$RUN_DIR"
	if [ ! -d "${RUN_DIR}/interface" ]; then
		mkdir "${RUN_DIR}/interface" || return 1
	fi
	command -v restorecon >/dev/null && restorecon "${RUN_DIR}/interface" "${RUN_DIR}/resolv.conf" "${RUN_DIR}/enable-updates"
	return 0
}

wipe_runtime_directories()
{
	[ -d "$RUN_DIR" ] || return 0
	rm -f "$RUN_DIR"/resolv.conf
	rm -f "$ENABLE_UPDATES_FLAGFILE"
	rm -f "$POSTPONED_UPDATE_FLAGFILE"
	rm -rf "${RUN_DIR}/interface/"*
	return 0
}

start()
{
	ebegin "Setting up resolvconf"
	wipe_runtime_directories
	create_runtime_directories || { eend 1 "Error creating runtime directories"; return 1; }
	:> "$POSTPONED_UPDATE_FLAGFILE" || { eend 1 "failed requesting update"; return 1; }
	resolvconf --enable-updates || { eend 1 "failed to enable updates"; return 1; }
	eend 0
	return 0
}

stop()
{
	ebegin "Stopping resolvconf"
	resolvconf --disable-updates || { eend 1 "failed to disable updates"; return 1; }
	eend 0
	return 0
}

reload()
{
	resolvconf -u || return 1
	return 0
}
