#!/bin/sh
#
# Deploy fresh/changed WL autogenerated DNS zones
#
GENESISROOT=`cd $(dirname $0)/..; pwd -P`
TOOLS="$GENESISROOT/tools"
CONFIG="$GENESISROOT/nodes"
STATIC="$GENESISROOT/dns"
DEPLOYROOT='/etc/namedb/master'

TFILE=`mktemp /tmp/$(basename $0).XXXXX`
trap "rm $TFILE; exit 1" 1 2 3 15

FORCE_UPDATE=${FORCE_UPDATE:-"no"}
ACTIVATE=${ACTIVATE:-"yes"}

# Generate new DNS and only complain/die on errors
(
  #svn up $GENESISROOT || exit 1
  #$TOOLS/genesis-to-yaml.pl $CONFIG/*/wleiden.conf || exit 1
  $TOOLS/gformat.py dns || exit 1
) 2>&1 > $TFILE || { cat $TFILE; exit 1; }


UPDATE_ZONES=""
# Check all zone files for vadility and updates
for NEW in $CONFIG/dns/*; do
  ZONE=`basename $NEW | cut -c 4-`  
  OLD=$DEPLOYROOT/`basename $NEW`

  # Syntax valid?
  named-checkzone -q $ZONE $NEW
  if [ $? -ne 0 ] ; then
    echo "# ERROR: $ZONE FAILED"
  else
    echo "# INFO: $ZONE - OK"
  fi

  if [ -r "$OLD" -a "$FORCE_UPDATE" = "no" ]; then
    # Contains new data?
    diff -I 'SOA' $OLD $NEW
    if [ $? -eq 0 ]; then
      continue
    fi
  fi

  # Deploy
  if [ "$ACTIVATE" = "yes" ]; then
    cp $NEW $OLD
    UPDATE_ZONES="$UPDATE_ZONES $ZONE"
  fi
done

# Make sure to reload if updates are executed
if [ -n "$UPDATE_ZONES" ]; then
  rndc reload
fi
