#! /bin/sh
#
# dnscheck [@seed nameserver] <FQDN>
#
# follows CNAME chain until it gets an A record
# unrolls A record name until it finds SOA (zone name)
# then queries each authoritative nameserver for the A record
# lists out all IP addresses returned per nameserver
#
# Mirrored from http://lanning.cc/pub/dnscheck.  Credit goes to
# Robert Hajime Lanning.  Note that this version of the script
# gives wrong results on unqualified second-level domains.


# default FQDN to lookup
LB_HOSTNAME="www.google.com"

# parse arguments
while [ "${#}" -gt "0" ]; do
   if [ "${1:0:1}" = "@" ]; then
      SEED="${1}"
   else
      LB_HOSTNAME="${1}"
   fi
   shift
done

# Follow CNAME chain
for CNAME in `dig ${SEED} ${LB_HOSTNAME} A +short|grep '\.$'`; do
   echo "CNAME: ${LB_HOSTNAME} -> ${CNAME}"
   LB_HOSTNAME="${CNAME}"
done

# unroll A record name, until SOA found
LB_DOMAIN="${LB_HOSTNAME#*.}"
while [ -n "${LB_DOMAIN}" ] && [ -z "`dig ${SEED} ${LB_DOMAIN} soa +short`" ]; do
   LB_DOMAIN="${LB_DOMAIN#*.}"
done

# report headers
echo "Host: ${LB_HOSTNAME}"
echo "Zone: ${LB_DOMAIN}"
echo "NameServer            IP List..."
echo "--------------------  ----------------"

# retrieve list of authoritative nameserver and iterate through them
# querying A records from each one and listing them out
dig ${SEED} ${LB_DOMAIN} ns +short | sort | uniq |\
while read NAMESERVER; do
   IPLIST="`dig \@${NAMESERVER} ${LB_HOSTNAME} A +short +norecurse | sed -e 's/^;; connection timed out.*$/TIMEOUT/' -e '/;.*$/d' | sort | xargs echo -n`"
   NAMESERVER="${NAMESERVER}                      "
   echo "${NAMESERVER:0:20}  ${IPLIST:-NXDOMAIN}"
done


