#!/bin/sh

PATH=/sbin:/bin:/usr/sbin:/usr/bin

# for a chrooted server: "-u bind -t /var/lib/named"
# Don't modify this line, change or create /etc/default/bind9.
OPTIONS=""

test -f /etc/default/rcS && . /etc/default/rcS
test -f /etc/default/bind9 && . /etc/default/bind9

# This function is here because it's possible that /var and / are on different partitions.
is_on_read_only_partition () {
    DIRECTORY=$1
    dir=`readlink -f $DIRECTORY`
    while true; do
	if [ ! -d "$dir" ]; then
	    echo "ERROR: $dir is not a directory"
	    exit 1
	else
	    for flag in `awk -v dir=$dir '{ if ($2 == dir) { print "FOUND"; split($4,FLAGS,",") } }; \
		END { for (f in FLAGS) print FLAGS[f] }' < /proc/mounts`; do
		[ "$flag" = "FOUND" ] && partition="read-write"
		[ "$flag" = "ro" ] && { partition="read-only"; break; }
	    done
	    if [ "$dir" = "/" -o -n "$partition" ]; then
		break
	    else
		dir=`dirname $dir`
	    fi
	fi
    done
    [ "$partition" = "read-only" ] && echo "yes" || echo "no"
}

bind_mount () {
    olddir=$1
    newdir=$2
    mkdir -p $olddir
    cp -a $newdir/* $olddir
    mount --bind $olddir $newdir
}

# Deal with read-only rootfs
if [ "$ROOTFS_READ_ONLY" = "yes" ]; then
    [ "$VERBOSE" != "no" ] && echo "WARN: start bind service in read-only rootfs"
    [ `is_on_read_only_partition /etc/bind` = "yes" ] && bind_mount /var/volatile/bind/etc /etc/bind
    [ `is_on_read_only_partition /var/named` = "yes" ] && bind_mount /var/volatile/bind/named /var/named
fi

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

case "$1" in
    start)
	echo -n "Starting domain name service: named"

	modprobe capability >/dev/null 2>&1 || true
	if [ ! -f /etc/bind/rndc.key ]; then
	    /usr/sbin/rndc-confgen -a -b 512 -r /dev/urandom
	    chmod 0640 /etc/bind/rndc.key
	fi
	if [ -f /var/run/named/named.pid ]; then
	    ps `cat /var/run/named/named.pid` > /dev/null && exit 1
	fi

	# dirs under /var/run can go away on reboots.
	mkdir -p /var/run/named
	mkdir -p /var/cache/bind
	chmod 775 /var/run/named
	chown root:bind /var/run/named >/dev/null 2>&1 || true

	if [ ! -x /usr/sbin/named ]; then
	    echo "named binary missing - not starting"
	    exit 1
	fi
	if start-stop-daemon --start --quiet --exec /usr/sbin/named \
		--pidfile /var/run/named/named.pid -- $OPTIONS; then
	    if [ -x /sbin/resolvconf ] ; then
		echo "nameserver 127.0.0.1" | /sbin/resolvconf -a lo
	    fi
	fi
	echo "."	
    ;;

    stop)
	echo -n "Stopping domain name service: named"
	if [ -x /sbin/resolvconf ]; then
	    /sbin/resolvconf -d lo
	fi
	/usr/sbin/rndc stop >/dev/null 2>&1
	echo "."	
    ;;

    reload)
	/usr/sbin/rndc reload
    ;;

    restart|force-reload)
	$0 stop
	sleep 2
	$0 start
    ;;
    
    *)
	echo "Usage: /etc/init.d/bind {start|stop|reload|restart|force-reload}" >&2
	exit 1
    ;;
esac

exit 0
