#!/bin/sh
#
# $OpenBSD: ndc.sh,v 1.12 1999/08/30 20:58:56 ho Exp $
#

default_chroot=/var/named

named_chroot=${named_chroot:-`. /etc/rc.conf ; echo "$named_chroot"`} 
named_user=`. /etc/rc.conf ; echo "$named_user"`
named_flags=`. /etc/rc.conf ; echo "$named_flags"`

named_daemon=/usr/sbin/named
named_ndc=/usr/libexec/named/ndc

if [ "X${named_chroot}" == "X" -a "X${named_flags}" != "XNO" ]; then
    named_chroot=${default_chroot}
    echo "ndc: named_chroot undefined or empty in /etc/rc.conf, using ${named_chroot} as chroot"
fi

named_start() {
    if [ "X${named_flags}" == "XNO" ]; then
	named_flags="";
    fi

    if [ "X${named_user}" != "X" -a "X${named_user}" != X"root" ]; then
	named_flags="-u ${named_user} ${named_flags}"
    fi

    if [ "X${named_chroot}" != "X" ]; then
	named_flags="-t ${named_chroot} ${named_flags}"
    fi

    $named_daemon $named_flags
    r_val=$?
    sleep 2
}

named_stop() {
    $named_ndc -q -c $named_channel stop
    r_val=$?
}

main() {
    if [ "X${named_chroot}" != "X" ]; then
	# handle chroot()-ed named
	named_channel=${named_chroot}/var/run/ndc

	case $1 in
	stop )
		named_stop
		;;
	restart | exec )
		named_stop
		named_start
		;;
	start )
		named_start
		;;
	* )
		exec $named_ndc -c $named_channel $@
	esac
    else
	# named is not running chroot()
	exec $named_ndc $@
    fi
}

main $@
exit $r_val
