#!/usr/bin/env python2.7
# Copyright 2015 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

"""Connect to a regiond's or clusterd's introspection service."""

from __future__ import (
    absolute_import,
    print_function,
    unicode_literals,
    )

str = None

__metaclass__ = type

import argparse
from glob import iglob
from os import execvp
from os.path import (
    basename,
    dirname,
    join,
)

# See http://docs.python.org/release/2.7/library/argparse.html.
argument_parser = argparse.ArgumentParser(description=__doc__)


def discover_introspectable_services():
    for socket in iglob("services/*/introspect"):
        yield basename(dirname(socket))


if __name__ == "__main__":
    services = sorted(discover_introspectable_services())
    if len(services) == 0:
        argument_parser.parse_known_args()  # For --help
        argument_parser.error(
            "No services are currently available for introspection. "
            "Start some with `make start` for example.\n")
    else:
        argument_parser.add_argument(
            "service", metavar="service", type=bytes, choices=services, help=(
                "The name of a MAAS service to introspect. Choose from: %s"
                % ", ".join(services)))
        args = argument_parser.parse_args()
        socket = join("services", args.service, "introspect")
        command = ("socat", "-,raw,echo=0", "unix-connect:%s" % socket)
        execvp("socat", command)
