#!/usr/bin/env python
#
# This file is a part of DNSViz, a tool suite for DNS/DNSSEC monitoring,
# analysis, and visualization.
# Created by Casey Deccio (casey@deccio.net)
#
# Copyright 2015-2016 VeriSign, Inc.
#
# Copyright 2016-2019 Casey Deccio
#
# DNSViz is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# DNSViz is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with DNSViz.  If not, see <http://www.gnu.org/licenses/>.
#

from __future__ import unicode_literals

import getopt
import importlib
import sys

def check_deps():
    # check dnspython dependency
    try:
        import dns.name
    except ImportError:
        sys.stderr.write('Error: dnspython does not appear to be installed\n')
        sys.exit(1)

def usage(err=None):
    if err is not None:
        err += '\n\n'
    else:
        err = ''
    sys.stderr.write('''%sUsage: dnsviz [options] <command> [args]
Options:
    -p <path>      - Add path to the python path.
Commands:
    probe          - Issue diagnostic DNS queries.
    grok           - Assess diagnostic DNS queries.
    graph          - Graph the assessment of diagnostic DNS queries.
    print          - Process diagnostic DNS queries to textual output.
    query          - Assess a DNS query.
    help [<command>]
                   - Show usage for a command.
''' % (err))

def main():
    check_deps()

    try:
        opts, args = getopt.getopt(sys.argv[1:], 'p:')
    except getopt.GetoptError as e:
        sys.stderr.write('%s\n' % str(e))
        sys.exit(1)

    opts = dict(opts)

    if len(args) < 1:
        usage()
        sys.exit(0)

    if args[0] == 'help':
        if len(args) < 2:
            usage()
            sys.exit(0)

        command = args[1]
    else:
        command = args[0]

    if '-p' in opts:
        sys.path.insert(0, opts['-p'])

    # first try importing just the commands module to make sure
    # dnsviz is properly reachable with the current path
    import dnsviz.commands

    # now try importing the module for the actual command
    try:
        mod = importlib.import_module('dnsviz.commands.%s' % command)
    except ImportError:
        # if there are more than two frames in the stack trace,
        # then the command was legit, but there was an ImportError
        # raised while running that command.
        exc_frame = sys.exc_info()[2]
        if exc_frame.tb_next.tb_next is not None:
            raise

        sys.stderr.write('Invalid command: %s\n' % command)
        sys.exit(1)

    if args[0] == 'help':
        mod.usage()
    else:
        mod.main(args)

if __name__ == "__main__":
    main()
