#! /usr/bin/python

# @file print-dns-configuration
#
# Copyright (C) Metaswitch Networks 2017
# If license terms are provided to you in a COPYING file in the root directory
# of the source code repository by which you are accessing this code, then
# the license outlined in that COPYING file applies to your use.
# Otherwise no rights are granted except for those provided to you by
# Metaswitch Networks in a separate written agreement.

import json, sys
from textwrap import dedent

# Expected format for the dns_config file
EXPECTED_FORMAT = dedent("""The expected format is:\n\
{
\"hostnames\" :
 [
   {
     \"name\" : \"<hostname 1>\",
     \"records\" : [{\"rrtype\": \"CNAME\", \"target\": \"<target for hostname 1>\"}]
   },
   {
     \"name\" : \"<hostname 1>\",
     \"records\" : [{\"rrtype\": \"CNAME\", \"target\": \"<target for hostname 1>\"}]
   },
   ...
 ]
}""")

source = sys.argv[1] if len(sys.argv) > 1 else "/etc/clearwater/dns.json"

# This does some basic validation of the dns configuration file, and
# prints the contents
try:
    with open(source) as dns_file:
        try:
            dns_data = json.load(dns_file)
            hostnames = dns_data["hostnames"]

            if hostnames:
                try:
                    for hostname in hostnames:
                        name = hostname["name"]
                        records = hostname["records"]

                        print "  Name: {}".format(name)
                        print "  Records:"
                        for record in records:
                            if record["rrtype"] != "CNAME":
                                print "Only CNAME records are supported"
                                raise KeyError
                            print "    rrtype: {}, target: {}".format(record["rrtype"], record["target"])
                        print ""

                except KeyError as e:
                    print "Invalid DNS entry detected in file.\n"
                    print EXPECTED_FORMAT

            else:
                print "Configuration file is present, but contains no entries.\n"
                print EXPECTED_FORMAT

        except ValueError, KeyError:
            print "\nInvalid DNS file at %s\n" % source
            print EXPECTED_FORMAT

except IOError:
    print "\nNo DNS file at %s\n" % source
