#!/bin/sh -e
### BEGIN INIT INFO
# Provides:          nsd
# Required-Start:    $syslog $remote_fs
# Required-Stop:     $syslog $remote_fs
# Should-Start:      $local_fs
# Should-Stop:       $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start NSD
# Description:       Provides an authoritative only Name Server Daemon.
### END INIT INFO

test -x /usr/sbin/nsd || exit 0

. /lib/lsb/init-functions

nsd_cfg() {
    res=$(/usr/sbin/nsd-checkconf -o "$1" /etc/nsd/nsd.conf)
    echo ${res:-"$2"}
}

nsdc_log() {
    log_begin_msg "$2"
    /usr/sbin/nsdc "$1" > /dev/null
    RET=$?
    log_end_msg $RET
    if [ "$RET" -ne 0 ]; then
	exit $RET
    fi
    return $RET
}

if test \! -f /etc/nsd/nsd.conf; then
    log_begin_msg "Missing /etc/nsd/nsd.conf configuration file."
    log_end_msg 0
    exit 0
fi

case "$1" in
    start)
        case "$(nsd_cfg pidfile)" in
            /run/nsd/*)
                mkdir -p /run/nsd && chown "$(nsd_cfg username nsd)" /run/nsd
                ;;
        esac
        if test \! -f "$(nsd_cfg database /var/lib/nsd/nsd.db)"; then
            nsdc_log rebuild "Building nsd zones..."
        fi
        nsdc_log start   "Starting nsd..."
        ;;
    stop)
        nsdc_log stop    "Stopping nsd..."
        ;;
    reload|rebuild|force-reload)
	nsdc_log rebuild "Building nsd zones..."
	nsdc_log reload  "Reloading nsd..."
	;;
    restart)
        nsdc_log restart "Restarting nsd..."
        ;;
    notify)
	nsdc_log notify  "Notifying nsd slaves..."
	;;
    update)
	nsdc_log update  "Updating nsd slave zones..."
        ;;
    *)
        opts=`grep '^ *[a-z|-]*)$' "$0" | tr -d ' \n' | tr ')' '|'`
        echo "Usage: /etc/init.d/nsd {${opts%|}}" >&2
        exit 1
        ;;
esac

exit $?
