#!/bin/bash

. /federated/lib/functions.sh

check_gluerecords() {
  echo -ne "\n* Checking glue records for $DOMAIN_NEW to match $EXTERNALIP.\n"
  # Setup DOMAIN variable for domain or subdomain
  DOMAIN_ARRAY=(${DOMAIN_NEW//./ })
  if [ "${#DOMAIN_ARRAY[@]}" -eq "2" ]; then
    DOMAIN_FIRST=${DOMAIN_ARRAY[0]}
    DOMAIN_LAST=${DOMAIN_ARRAY[1]}
  elif [ "${#DOMAIN_ARRAY[@]}" -eq "3" ]; then
    DOMAIN_FIRST=${DOMAIN_ARRAY[0]}
    DOMAIN_MIDDLE=${DOMAIN_ARRAY[1]}
    DOMAIN_LAST=${DOMAIN_ARRAY[2]}
  else
    failcheck "$DOMAIN_NEW is not a valid domain.com or sub.domain.com"
  fi

  NS_PARENT="$(dig +short NS "$DOMAIN_LAST." | head -n 1)"
  CHECK_NS1=`dig +noall +authority +additional +norecurse @"$NS_PARENT" NS "$DOMAIN_NEW". | grep NS | grep -i ns1.$DOMAIN_NEW`
  [ $? -ne 0 ] && failcheck "Couldn't find glue / authoritative NS record ns1.$DOMAIN_NEW"

  CHECK_NS2=`dig +noall +authority +additional +norecurse @"$NS_PARENT" NS "$DOMAIN_NEW". | grep NS | grep -i ns2.$DOMAIN_NEW`
  [ $? -ne 0 ] && failcheck "Couldn't find glue / authoritative NS record ns2.$DOMAIN_NEW"

  CHECK_A1=`dig +noall +authority +additional +norecurse @"$NS_PARENT" NS "$DOMAIN_NEW". | grep A | grep -i ns1.$DOMAIN_NEW | grep $EXTERNALIP`
  [ $? -ne 0 ] && failcheck "Couldn't find glue / authoritative A record ns1.$DOMAIN_NEW to $EXTERNALIP"

  CHECK_A2=`dig +noall +authority +additional +norecurse @"$NS_PARENT" NS "$DOMAIN_NEW". | grep A | grep -i ns2.$DOMAIN_NEW | grep $EXTERNALIP`
  [ $? -ne 0 ] && failcheck "Couldn't find glue / authoritative A record ns2.$DOMAIN_NEW to $EXTERNALIP"

  echo -ne "* Glue records are correct!\n\n"
}

usage() {
  echo "$0: <domain.com>"
  exit 2
}

[ $# != 1 ] && usage
DOMAIN_NEW=$1
EXTERNALIP=`dig @resolver4.opendns.com myip.opendns.com +short 2> /dev/null`
[ $? -ne 0 ] && failcheck "Couldn't run dig, dns is not working"
check_gluerecords
