#!/bin/sh
#
# $NetBSD: tinydns.sh,v 1.10 2019/01/07 14:01:55 schmonz Exp $
#
# djbdns-run-20250402 script to control tinydns (authoritative DNS service).
#

# PROVIDE: tinydns named
# REQUIRE: NETWORKING mountcritremote syslogd
# BEFORE:  DAEMON

name="tinydns"

# User-settable rc.conf variables and their default values:
: ${tinydns_postenv:=""}
: ${tinydns_ip:="0.0.0.0"}
: ${tinydns_datalimit:="300000"}
: ${tinydns_autocdb:="YES"}
: ${tinydns_log:="YES"}
: ${tinydns_logcmd:="logger -t nbdjbdns/tiny -p daemon.info"}
: ${tinydns_nologcmd:="/usr/pkg/bin/multilog -*"}

tinydns_data="/usr/pkg/etc/${name}/data"

if [ -f /etc/rc.subr ]; then
	. /etc/rc.subr
fi

rcvar=${name}
required_files="${tinydns_data}"
command="/usr/pkg/bin/${name}"
procname=nb${name}
start_precmd="tinydns_precmd"
extra_commands="cdb reload"
cdb_cmd="tinydns_cdb"
reload_cmd=${cdb_cmd}

tinydns_precmd() {
	if [ -f /etc/rc.subr ] && ! checkyesno tinydns_log; then
		tinydns_logcmd=${tinydns_nologcmd}
	fi
	if [ -f /etc/rc.subr ] && checkyesno tinydns_autocdb; then
		tinydns_needcdb && tinydns_cdb
	fi
	command="/usr/pkg/bin/pgrphack /usr/bin/env - ${tinydns_postenv} \
ROOT=/usr/pkg/etc/${name} \
IP=${tinydns_ip} \
/usr/pkg/bin/envuidgid tinydns \
/usr/pkg/bin/softlimit -d ${tinydns_datalimit} \
/usr/pkg/bin/argv0 /usr/pkg/bin/${name} ${procname} \
</dev/null 2>&1 | \
/usr/pkg/bin/pgrphack /usr/pkg/bin/setuidgid dnslog ${tinydns_logcmd}"
	command_args="&"
	rc_flags=""
}

tinydns_needcdb() {
	_src=${tinydns_data}
	_dst=${tinydns_data}.cdb
	[ -f "${_src}" -a "${_src}" -nt "${_dst}" ] || [ ! -f "${_dst}" ]
}

tinydns_cdb() {
	echo "Reloading ${tinydns_data}."
	cd /usr/pkg/etc/${name} && /usr/pkg/bin/tinydns-data
	/bin/chmod 644 ${tinydns_data}.cdb
}

if [ -f /etc/rc.subr ]; then
	load_rc_config $name
	run_rc_command "$1"
else
	echo -n " ${name}"
	tinydns_precmd
	eval ${command} ${tinydns_flags} ${command_args}
fi
