#!/bin/sh

export PATH=/bin:/sbin:/usr/bin:/usr/sbin
# Copying files from the dnsmanagerd bind9 directory to the powerdns directory.
PDNSDIR="/var/powerdns/"
DNSMANDIR="/tmp/DATA-dnsmanagerd/bind9-zones/"
LOGFILE="/tmp/invalid-domains"

test_domain_validity() {
	named-checkzone $1 $DNSMANDIR/$1 1>/dev/null 2>/dev/null
}

local_update() {
	echo "update domain $1"
	# Simulate what is done with dnsmanagerd to avoir file corruption.
	cp $DNSMANDIR/$1 $PDNSDIR/$1.wip
	mv $PDNSDIR/$1.wip $PDNSDIR/$1
}

local_delete() { echo "delete domain $1" ; rm $PDNSDIR/$1 ; }

action() {
	event=$1
	file=$2

	echo $event | grep "MOVED_TO" >/dev/null
	if [ $? -eq 0 ]; then
		test_domain_validity $file
		if [ $? -eq 0 ]; then
			local_update $file
		else
			echo "invalid domain: $file" >> $LOGFILE
		fi
	fi

	echo $event | grep "DELETE" >/dev/null
	if [ $? -eq 0 ]; then
		local_delete $file
	fi
}

# NOTE: dnsmanagerd writes bind9 files in $DNSMANDIR and with a suffix ".wip" then moves them
#       to remove the suffix. This way, the final file is expected to never be corrupted,
#       for example by copying it to the secondary DNS server while the zone not being
#       fully written to the file.
#
# Therefore, the different interesting actions we should monitor are:
# - moved_to: a zone file has been modified
# - delete: a domain has been removed
opts="-e moved_to -e delete -m"
echo "inotifywait ${opts} --format '%:e %f' $DNSMANDIR"
inotifywait ${opts} --format '%:e %f' $DNSMANDIR | while read LINE; do action $LINE ; done