#!/usr/bin/python
# Copyright (C) 2019 Red Hat, Inc., Jake Hunsaker <jhunsake@redhat.com>

# This file is part of the rig project: https://github.com/TurboTurtle/rig
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# version 2 of the GNU General Public License.
#
# See the LICENSE file in the source distribution for further information.

import argparse
import inspect
import os
import sys

from rigging import Rigging
from rigging.rigs import BaseRig


def _import_modules(modname):
    """
    Import helper to import all classes from a rig definition.
    """
    mod_short_name = modname.split('.')[2]
    module = __import__(modname, globals(), locals(), [mod_short_name])
    _modules = inspect.getmembers(module, inspect.isclass)
    modules = []
    for mod in _modules:
        if not isinstance(mod, list):
            mod = [mod]
        for _mod in mod:
            if _mod[0] in ('Rigging', 'BaseRig'):
                continue
            if not issubclass(_mod[1], BaseRig):
                continue
            modules.append(_mod)
    return modules


def _load_supported_rigs():
    """
    Discover locally available resource monitor types.

    Monitors are added to a dict that is later iterated over to check if
    the requested monitor is one that we have available to us.
    """
    import rigging.rigs
    monitors = rigging.rigs
    _supported_rigs = {}
    modules = []
    for path in monitors.__path__:
        if os.path.isdir(path):
            for pyfile in sorted(os.listdir(path)):
                if not pyfile.endswith('.py') or '__' in pyfile:
                    continue
                fname, ext = os.path.splitext(pyfile)
                _mod = "rigging.rigs.%s" % fname
                modules.extend(_import_modules(_mod))
    for mod in modules:
        _supported_rigs[mod[0].lower()] = mod[1]
    return _supported_rigs


if __name__ == '__main__':

    supported_rigs = _load_supported_rigs()

    desc = ('Rig is used to monitor a resource for a specific trigger and then'
            ' execute a user-defined action.')
    usage = """
    rig <subcmd> <options>

    <subcmd> may be one of the following:

        destroy         Destroy a specified rig
        info            Get detailed information on a deployed rig
        list            Get a list of currently deployed rigs
        trigger         Manually trigger a deployed rig right now


    """

    for _rig in supported_rigs:
        usage += "\t{name:<15}\t{desc}\n".format(
            name=_rig,
            desc=supported_rigs[_rig].parser_description
        )

    epilog = """
    For more information on the types of rigs and the options available to them
    use rig <subcmd> --help.
    E.G. 'rig logs --help'
    """

    parser = argparse.ArgumentParser(description=desc, usage=usage,
                                     epilog=epilog)
    parser.add_argument('subcmd', help='subcommand to execute')
    parser.add_argument('-i', '--id', help='rig id for info or destroy',
                        default='-1')
    parser.add_argument('--force', action='store_true',
                        help='force deletion of requested rig(s)')
    args = vars(parser.parse_args(sys.argv[1:2]))

    if os.getuid() == 0:
        try:
            rig = Rigging(parser, args, supported_rigs)
            ret = rig.execute()
            sys.exit(ret)
        except SystemExit:
            pass
    else:
        print("Rig must be run as the root user.")
        sys.exit(1)
