#! /usr/bin/python

# @file print-enum-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 ENUM file
EXPECTED_FORMAT = dedent("""The expected format is:\n\
{
\"number_blocks\" :
 [
   {
     \"name\" : \"<name>\",
     \"prefix\" : \"<prefix>\",
     \"regex\" : \"<regex>\"
   },
   ...
 ]
}""")

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

# This does some basic validation of the ENUM configuration file, and
# prints the contents
try:
    with open(source) as enum_file:
        try:
            enum_data = json.load(enum_file)
            blocks = enum_data["number_blocks"]

            if blocks:
                try:
                    for block in blocks:
                        name = block["name"]
                        prefix = block["prefix"]
                        regex = block["regex"]

                        print "  Name: {}".format(name)
                        print "  Prefix: {}".format(prefix)
                        print "  Regex: {}".format(regex)
                        print ""

                except KeyError as e:
                    print "Invalid ENUM 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 ENUM file at %s\n" % source
            print EXPECTED_FORMAT

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