#!/usr/bin/env python
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2011-2019  Contributor
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import print_function

import sys
import os
import getopt

try:
    import ms.version
except ImportError:
    pass
else:
    ms.version.addpkg('setuptools', '0.6c11')
    ms.version.addpkg('protobuf', '2.6.1')

# -- begin path_setup --
BINDIR = os.path.dirname(os.path.realpath(__file__))
LIBDIR = os.path.join(BINDIR, "..", "lib")

if LIBDIR not in sys.path:
    sys.path.append(LIBDIR)
# -- end path_setup --

from google.protobuf.text_format import PrintMessage

from aquilon.worker import depends  # pylint: disable=W0611
from aquilon.config import Config, lookup_file_path

if not os.environ.get("AQDCONF"):
    os.environ["AQDCONF"] = lookup_file_path("aqd.conf.defaults")

config = Config()
sys.path.append(config.get("protocols", "directory"))

import aqdaudit_pb2
import aqddnsdomains_pb2
import aqdentitlements_pb2
import aqdlocations_pb2
import aqdnetworks_pb2
import aqdparamdefinitions_pb2
import aqdparameters_pb2
import aqdservices_pb2
import aqdsystems_pb2


def usage():
    print("""
    %s [--help] [--file INPUT] --type TYPE

    --help      this message
    --file      input file containing the message, default: stdin
    --type      type of the message

    Example: aq show network --ip 1.2.3.4 --format proto | %s --type network
""" % (sys.argv[0], sys.argv[0]), file=sys.stderr)

try:
    opts, args = getopt.getopt(sys.argv[1:], "f:ht:",
                               ["file=", "help", "type="])
except getopt.GetoptError as e:
    print(str(e), file=sys.stderr)
    usage()
    sys.exit(2)

typemap = {
    "dns_domain": aqddnsdomains_pb2.DNSDomainList(),
    "domain": aqdsystems_pb2.DomainList(),
    "host": aqdsystems_pb2.HostList(),
    "machine": aqdsystems_pb2.MachineList(),
    "model": aqdsystems_pb2.ModelList(),
    "cluster": aqdsystems_pb2.ClusterList(),
    "metacluster": aqdsystems_pb2.MetaClusterList(),
    "archetype": aqdsystems_pb2.ArchetypeList(),
    "personality": aqdsystems_pb2.PersonalityList(),
    "operating_system": aqdsystems_pb2.OperatingSystemList(),
    "network": aqdnetworks_pb2.NetworkList(),
    "service": aqdservices_pb2.ServiceList(),
    "service_map": aqdservices_pb2.ServiceMapList(),
    "location": aqdlocations_pb2.LocationList(),
    "transaction": aqdaudit_pb2.TransactionList(),
    "parameter": aqdparameters_pb2.ParameterList(),
    "parameter_definition": aqdparamdefinitions_pb2.ParamDefinitionList(),
    "resource": aqdsystems_pb2.ResourceList(),
    "feature": aqdsystems_pb2.FeatureList(),
    "virtual_switch": aqdsystems_pb2.VirtualSwitchList(),
    "network_device": aqdsystems_pb2.NetworkDeviceList(),
    "location_preference": aqdsystems_pb2.LocationPreferenceList(),
    'dynamic_range': aqdsystems_pb2.DynamicRangeList(),
}

input = sys.stdin
if hasattr(input, "buffer"):
    # Python 3: avoid text encoding
    input = input.buffer
msg = None

for opt, arg in opts:
    if opt in ("-f", "--file"):
        input = open(arg)
    elif opt in ("-h", "--help"):
        usage()
        sys.exit(0)
    elif opt in ("-t", "--type"):
        if arg not in typemap:
            assert False, "unknown type %s" % arg
        msg = typemap[arg]
    else:
        assert False, "unhandled option '%s'" % opt

if not msg:
    assert False, "type not specified"

raw_msg = input.read()
msg.ParseFromString(raw_msg)
PrintMessage(msg, sys.stdout)
