:
# NAME:
#	getdb - getdata from named
#
# DESCRIPTION:
#	We ask named(8) to dump its cache, wait for it to finish, then
#	run getdata(1) to extract useful information in a form that
#	facilitates further processing.
#
#	This saves us having to provide a client that can query a
#	named on a non-standard port. 
#	
# AUTHOR:
#	Simon J. Gerraty <sjg@crufty.net>

# RCSid:
#	$Id: getdb,v 1.16 2023/06/11 06:22:06 sjg Exp $
#
#	@(#) Copyright (c) 1997-2022 Simon J. Gerraty.
#
#	This file is provided in the hope that it will
#	be of use.  There is absolutely NO WARRANTY.
#	Permission to copy, redistribute or otherwise
#	use this file is hereby granted provided that 
#	the above copyright notice and this notice are
#	left intact. 
#      
#	Please send copies of changes and bug-fixes to:
#	sjg@crufty.net
#

Myname=getdb
Mydir=`dirname $0`

PATH=$PATH:$Mydir

. debug.sh

DebugOn $Myname

x=0
if test "x$NO_NAMED" = x; then
	DNSMAGIC=${DNSMAGIC:-${SHARE:-${LOCAL:-/usr/local}/share}/dns}

	$_SOURCE_SH . source.sh

	Mydir=${Mydir:-`dirname $0`}

	DebugOn $Myname:setup

	_source getndlog.sh $Mydir:$PATH

	DebugOff $Myname:setup

	# if we were not called by regress...
	if test "x$ND_PID" = x; then
		#
		# make sure named is running
		#
		$RC_D/named check
		#
		# now get its pid and working directory
		#
		. dnsfuncs.sh
		ND_PID=`dnsPid`
		ND_STARTPID=$ND_PID
	fi
	#	
	# ask named to dump its cache
	# this can take a couple of minutes!
	#
	case "${BINDVERS:-9}" in
	9*)	# bind9 doesn't log anything, but rndc appears to only
		# exit after the operation has completed.
		# This only works for 9.3+
		if [ -s rndc.key ]; then
			RNDC_FLAGS="-c rndc.key -y rndc-key -s localhost"
		fi
		${NDC:-rndc} ${RNDC_FLAGS} ${NDC_PORT:+-p} ${NDC_PORT} -s localhost dumpdb ${BIND9_DUMPDB_MODE:--all} 2>/dev/null || exit 1
		ok=finished
		;;
	*)	kill -INT $ND_PID 2>/dev/null
		ND_LOG=${ND_LOG:-${TMP:-/tmp}/ndl$$}

		for i in 1 2 4 8 16 32 64
		do
			GetNamedLog > $ND_LOG
			ok=`grep dumping $ND_LOG | tail -1`
			case "$ok" in
			*finish*) break;;
			esac
			sleep $i
		done
		;;
	esac
	#
	# work out where it went
	#
	for d in $ND_DIR $DNSDIR /var/tmp /usr/tmp
	do
		test "$ND_DUMP" && break	
		if test -f $d/named_dump.db; then
			ND_DUMP=$d/named_dump.db
		fi
	done

	case "$ok" in
	*finish*) ;;
	"") echo "$Myname: failed to get ${ND_DUMP:-named_dump.db}" >&2; exit 1;;
	esac

	[ "$ND_DUMP" ] || { echo "$Myname: don't know where named_dump.db is" >&2; exit 1; }
	ND_DUMP=${ND_DUMP:-/usr/tmp/named_dump.db}
	GETDATA=${GETDATA:-`Which -x getdata $DNSMAGIC/bin:$PATH`}
	if [ "$GETDATA" ]; then
		: saving to ${ND_DATA:-/tmp/nd_data}
		${GETDATA:-getdata} $ND_DUMP > ${ND_DATA:-/tmp/nd_data}
		x=$?
	fi
fi
exit $x
