#!/bin/bash

# For each zone (each file in $BASE), fetches the zone from the
# nameserver via AXFR and feeds it to bind's dnssec-verify to see of things are
# sane.
#
# By default BASE is set via the indir option from the yaml file /etc/dns-helpers.yaml

# Copyright 2016 Peter Palfrader
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

set -e
set -u

BASE=$(perl -mYAML -e 'my ($hashref, $arrayref, $string) = YAML::LoadFile($ARGV[0]); print $hashref->{'indir'},"\n"' /etc/dns-helpers.yaml)
if [ -z "$BASE" ] || ! [ -d "$BASE" ] ; then
	echo "Basedir $BASE is not a directory."
	exit 3
fi

EXTRA="-b 127.0.0.1"
MASTER=$(hostname -f)

zones=$(mktemp)
tmp=$(mktemp)
extra=$(mktemp)
trap "rm -f '$zones' '$tmp' '$extra'" EXIT

err=0
errmsg=""
num=0

for zone in $(find "$BASE" -maxdepth 1 -mindepth 1 -type f -printf "%f\n" | sort); do
	if dig $EXTRA -t axfr @"$MASTER" "$zone" | /usr/sbin/dnssec-verify -o "$zone" /dev/stdin > "$tmp" 2>&1; then
		num=$((num + 1))
	else
		err=2
		errmsg="$errmsg $zone"
		cat "$tmp" >> "$extra"
	fi
done < "$zones"

if [ "$err" = 0 ]; then
	if [ "$num" = 0 ]; then
		echo "OK: No zones found?"
		err=1
	else
		echo "OK: $num zones appear to be OK."
	fi
else
	echo "CRITICAL:$errmsg"
	cat "$extra"
fi
exit "$err"
