#!/usr/local/bin/python2.7

import importlib
import os
import re
import sys

from ripe.atlas.tools.commands.base import Command
from ripe.atlas.tools.exceptions import RipeAtlasToolsException


class RipeAtlas(object):

    def __init__(self):
        self.command = None
        self.args = []
        self.kwargs = {}

    def _setup_command(self):

        caller = os.path.basename(sys.argv[0])
        shortcut = re.match('^a(ping|traceroute|dig|sslcert|ntp|http)$', caller)

        available_commands = Command.get_available_commands()
        if shortcut:
            self.command = "measure"
            sys.argv.insert(1, self._translate_shortcut(shortcut.group(1)))
        else:
            if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help"):
                raise RipeAtlasToolsException(
                    "Usage: ripe-atlas <{}> [arguments]".format(
                        "|".join(set(available_commands) - {"shibboleet"})
                    )
                )
            self.command = sys.argv.pop(1)

    @staticmethod
    def _translate_shortcut(shortcut):
        if shortcut == "dig":
            return "dns"
        return shortcut

    def main(self):

        self._setup_command()

        module_name = "ripe.atlas.tools.commands.{}".format(self.command)

        try:
            module = importlib.import_module(module_name)

        except ImportError as exc:
            if hasattr(exc, "name"):
                # Python 3.3+, exc.name will be the full module path
                is_command_module = exc.name == module_name
            else:
                # Python 2.7, message will contain the final part of the path
                is_command_module = exc.args[0].rsplit(
                    " ", 1)[-1] == self.command
            if is_command_module:
                raise RipeAtlasToolsException("No such command.")
            else:
                raise  # We're missing a dependency
        #
        # If the imported module contains a `Factory` class, execute that
        # to get the `cmd` we're going to use.  Otherwise, we expect there
        # to be a `Command` class in there.
        #

        if hasattr(module, "Factory"):
            cmd = module.Factory(*self.args, **self.kwargs).create()
        else:
            cmd = module.Command(*self.args, **self.kwargs)

        cmd.init_args()
        cmd.run()


if __name__ == '__main__':
    try:
        sys.exit(RipeAtlas().main())
    except RipeAtlasToolsException as e:
        e.write()
        raise SystemExit()
