#!/bin/ksh
#ident "@(#)unixsrc:usr/src/common/cmd/cmd-inet/usr.sbin/bind/local/ndc/ndc /main/2"

status() {
	ps -ef | fgrep in.named | fgrep -v fgrep > /dev/null 2>&1
}

start() {
	/usr/sbin/in.named
}

rndc() {
	/usr/sbin/rndc $*
}

#
#-IF the, include, statement for the security keys does not exist in the
# DNS/BIND configuration file
#    -Add the, include, statement to the DNS/BIND configuration file
#-FI
#-TODO:
#--Make this work if with, include, statements whose file path is other then the
#  default path for including security keys.
#
updateNamedConfig=0
if [[ (-e /etc/inet/named.conf) ]]
then
    fgrep "include \"/etc/inet/named.d/.security.d/key.include\"" \
     /etc/inet/named.conf >/dev/null 2>&1
    if [[ $? -ne 0 ]]
    then
	updateNamedConfig=1
	echo "include \"/etc/inet/named.d/.security.d/key.include\" ;" >>/etc/inet/named.conf
    fi
fi

#
#-IF the default configuration file does not exist OR the include statements
# file path does not exist
#    -Create rndc configuration file and/or include statements file path
#     via rndc-keyadm(1Mtcp).
#-FI
#-TODO:
#--Make this work if with configuration files other then the default location.
#
namedNotRunning=NOTSET
if [[ (! -e /etc/inet/rndc.conf) || \
 (! -e /etc/inet/named.d/.security.d/key.include) ]]
then
    #
    #-The following steps are necessary since a new secret key may be generated
    # when creating the rndc.conf and/or files included by the key.include file.
    # If the in.named is running and a new secret key is generated when
    # creating the rndc.conf and/or key.include files, subsequent ndc/rndc
    # command to the localhost will fail.
    #--stop in.named if already running before creating the rndc.conf and/or
    #  key.include file.
    #--start in.named after creating rndc.conf and/or key.include file. 
    status
    namedRunning=$?
    if [[ $namedRunning -eq 0 ]]
    then
	rndc stop
    fi
    rndc-keyadm -a >/dev/null 2>&1
fi

#
#-IF in.named was previosly running before rndc-keyadm(1Mtcp) was executed
#	-start the in.named 
#-ELSEIF DNS/BIND configuration was changed and in.named is running
#	-reload the in.named
#-FI
if [[  "$namedRunning" = "0" ]]
then
    start
elif [[ ($updateNamedConfig -eq 1) && ("#namedRunning" = "NOTSET") ]]
then
    status && rndc reload
fi




case "$*" in
status)
	status;;
start)
	status || start;;
restart)
	status && rndc stop
	start;;
*)
	status && rndc $*;;
esac

