#!/bin/sh
#
# $NetBSD: axfrdns.sh,v 1.11 2020/10/16 09:28:15 schmonz Exp $
#
# djbdns-run-20250402 script to control axfrdns (DNS zone-transfer and TCP service).
#

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

name="axfrdns"

# User-settable rc.conf variables and their default values:
: ${axfrdns_postenv:=""}
: ${axfrdns_ip:="0.0.0.0"}
: ${axfrdns_datalimit:="300000"}
: ${axfrdns_pretcpserver:=""}
: ${axfrdns_tcpserver:="/usr/pkg/bin/tcpserver"}
: ${axfrdns_tcpflags:="-vDRHl0"}
: ${axfrdns_tcprules:="/usr/pkg/etc/axfrdns/tcp"}
: ${axfrdns_autocdb:="YES"}
: ${axfrdns_tcpport:="53"}
: ${axfrdns_log:="YES"}
: ${axfrdns_logcmd:="logger -t nbdjbdns/axfr -p daemon.info"}
: ${axfrdns_nologcmd:="/usr/pkg/bin/multilog -*"}

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

rcvar=${name}
required_files="${axfrdns_tcprules}"
command="${axfrdns_tcpserver}"
procname=nb${name}
start_precmd="axfrdns_precmd"
extra_commands="cdb reload"
cdb_cmd="axfrdns_cdb"
reload_cmd=${cdb_cmd}

axfrdns_precmd() {
	if [ -f /etc/rc.subr ] && ! checkyesno axfrdns_log; then
		axfrdns_logcmd=${axfrdns_nologcmd}
	fi
	if [ -f /etc/rc.subr ] && checkyesno axfrdns_autocdb; then
		axfrdns_needcdb && axfrdns_cdb
	fi
	# tcpserver(1) is akin to inetd(8), but runs one service per process.
	# We want to signal only the tcpserver process responsible for this
	# service. Use argv0(1) to set procname to "nbaxfrdns".
	command="/usr/pkg/bin/pgrphack /usr/bin/env - ${axfrdns_postenv} \
ROOT=/usr/pkg/etc/tinydns \
IP=${axfrdns_ip} \
/usr/pkg/bin/envuidgid axfrdns \
/usr/pkg/bin/softlimit -d ${axfrdns_datalimit} ${axfrdns_pretcpserver} \
/usr/pkg/bin/argv0 ${axfrdns_tcpserver} ${procname} \
${axfrdns_tcpflags} -x ${axfrdns_tcprules}.cdb \
-- \
${axfrdns_ip} ${axfrdns_tcpport} \
/usr/pkg/bin/${name} \
</dev/null 2>&1 | \
/usr/pkg/bin/pgrphack /usr/pkg/bin/setuidgid dnslog ${axfrdns_logcmd}"
	command_args="&"
	rc_flags=""
}

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

axfrdns_cdb() {
	echo "Reloading ${axfrdns_tcprules}."
	/usr/pkg/bin/tcprules ${axfrdns_tcprules}.cdb ${axfrdns_tcprules}.tmp < ${axfrdns_tcprules}
	/bin/chmod 644 ${axfrdns_tcprules}.cdb
}

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