#!/usr/bin/env python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Mathias Kettner 2020             mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk 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 in version 2.  check_mk is  distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY;  with-
# out even the implied warranty of  MERCHANTABILITY  or  FITNESS FOR A
# PARTICULAR PURPOSE. See the  GNU General Public License for more de-
# tails. You should have  received  a copy of the  GNU  General Public
# License along with GNU Make; see the file  COPYING.  If  not,  write
# to the Free Software Foundation, Inc., 51 Franklin St,  Fifth Floor,
# Boston, MA 02110-1301 USA.

import re
import sys
import getopt
import urllib3
from requests.packages.urllib3.exceptions import InsecureRequestWarning


def usage():
    sys.stderr.write("""Check_MK Hitachi VSP

USAGE: agent_hitachivsp [OPTIONS] HOST

OPTIONS:
  -h, --help                    Show this help message and exit
  --address                     Host address
  --user                        Username
  --password                    Password
  --no-cert-check               Disable certificate check
""")
    sys.exit(1)

short_options = "h"
long_options  = ["help", "username=", "password=", "address=", "demo", "no-cert-check"]

try:
    opts, args = getopt.getopt(sys.argv[1:], short_options, long_options)
except getopt.GetoptError as err:
    sys.stderr.write("%s\n" % err)
    sys.exit(1)


opt_demo = False
opt_cert = True
args_dict = {}

for o,a in opts:
    if o in [ "--address" ]:
        args_dict["address"] = a
    elif o in [ "--username" ]:
        args_dict["username"] = a
    elif o in [ "--password" ]:
        args_dict["password"] = a
    elif o in [ "--demo" ]:
        opt_demo = True
    elif o in [ "--no-cert-check" ]:
        opt_cert = False
    elif o in [ "-h", "--help" ]:
        usage()


def query(url):
    if opt_cert == False:
        requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    response     = requests.get(url, auth = (args_dict["username"], args_dict["password"]), verify=opt_cert)
    raw_xml      = response.text
    # Remove namespace nonsense
    raw_xml      = re.sub(' xmlns="[^"]+"', '', raw_xml, count=1)
#    raw_xml = re.sub(' http-equiv="[^"]+"', '', raw_xml, count=1)
    xml_instance = ET.fromstring(raw_xml)
    return xml_instance


output_lines = []
def output(line):
    if type(line) not in [str]:
        output_lines.append(pprint.pformat(line))
    else:
        output_lines.append(line)


def process_cluster_info():
    output("<<<storeonce_clusterinfo:sep(9)>>>")
    xml_instance = query_cluster_info()
    tbody = xml_instance.find("body").find("div").find("table").find("tbody")
    for child in tbody:
        name  = child[0].text
        value = child[1].text
        output("%s\t%s" % (name, value))


def query_cluster_info():
    if opt_demo:
        raw_xml      = re.sub(' xmlns="[^"]+"', '', cluster_xml, count=1)
        return ET.fromstring(raw_xml)
    url = "https://%(address)s/storeonceservices/cluster/" % args_dict
    return query(url)

serviceset_ids = set()
def process_servicesets():
    output("<<<storeonce_servicesets:sep(9)>>>")
    xml_instance = query_servicesets()
    servicesets = xml_instance.find("body").find("div")
    for element in servicesets:
        tbody = element.find("table").find("tbody")
        serviceset_id = tbody[0][1].text
        serviceset_ids.add(serviceset_id)
        output("[%s]" % serviceset_id)
        for child in tbody:
            name  = child[0].text
            value = child[1].text
            output("%s\t%s" % (name, value))


def query_servicesets():
    if opt_demo:
        raw_xml = re.sub(' xmlns="[^"]+"', '', servicesets_xml, count=1)
        return ET.fromstring(raw_xml)
    url = "https://%(address)s/storeonceservices/cluster/servicesets/" % args_dict
    return query(url)


def process_stores_info():
    output("<<<storeonce_stores:sep(9)>>>")
    for serviceset_id in serviceset_ids:
        xml_instance = query_stores_info(serviceset_id)
        stores = xml_instance.find("body").find("div")
        for element in stores:
            tbody = element.find("table").find("tbody")
            store_id = tbody[0][1].text
            output("[%s/%s]" % (serviceset_id, store_id))
            serviceset_ids.add(serviceset_id)
            for child in tbody:
                name  = child[0].text
                value = child[1].text
                output("%s\t%s" % (name, value))


def query_stores_info(serviceset_id):
    if opt_demo:
        raw_xml = re.sub(' xmlns="[^"]+"', '', stores_xml, count=1)
        return ET.fromstring(raw_xml)

    url = "https://%(address)s/storeonceservices/cluster/servicesets/" % args_dict + \
            "%s/services/cat/stores/" % serviceset_id
    return query(url)

serviceset_ids_teaming = set()
def process_servicesets_teaming():
    output("<<<storeonce_servicesets_team:sep(9)>>>")
    xml_instance = query_servicesets_teaming()
    servicesets_teaming = xml_instance.find("body").find("div")
    for element in servicesets_teaming:
        tbody = element.find("table").find("tbody")
        serviceset_id_teaming = tbody[0][1].text
        serviceset_ids_teaming.add(serviceset_id_teaming)
        output("[%s]" % serviceset_id_teaming)
        for child in tbody:
            name  = child[0].text
            value = child[1].text
            output("%s\t%s" % (name, value))


def query_servicesets_teaming():
    if opt_demo:
        raw_xml = re.sub(' xmlns="[^"]+"', '', servicesets_xml, count=1)
        return ET.fromstring(raw_xml)
    url = "https://%(address)s/storeonceservices/cluster/servicesets/1/teaming/services/cat/stores" % args_dict
    return query(url)


def process_stores_info_teaming():
    output("<<<storeonce_stores_team:sep(9)>>>")
    for serviceset_id_teaming in serviceset_ids_teaming:
        xml_instance = query_stores_info_teaming(serviceset_id_teaming)
        stores = xml_instance.find("body").find("div")
        for element in stores:
            tbody = element.find("table").find("tbody")
            store_id = tbody[0][1].text
            output("[%s/%s]" % (serviceset_id_teaming, store_id))
            serviceset_ids_teaming.add(serviceset_id_teaming)
            for child in tbody:
                name  = child[0].text
                value = child[1].text
                output("%s\t%s" % (name, value))



def query_stores_info_teaming(serviceset_id):
    if opt_demo:
        raw_xml = re.sub(' xmlns="[^"]+"', '', stores_xml_teaming, count=1)
        return ET.fromstring(raw_xml)

    url = "https://%(address)s/storeonceservices/cluster/servicesets/" % args_dict + \
            "1/teaming/services/cat/stores/%s" % serviceset_id
    return query(url)





def main():
    try:
        # Get cluster info
        process_cluster_info()

        # Get servicesets
        process_servicesets()

        # Get stores info
        process_stores_info()

        process_servicesets_teaming()
        process_stores_info_teaming()

        sys.stdout.write("\n".join(output_lines) + "\n")
    except Exception as e:
        sys.stderr.write("Connection error: %s" % e)
        sys.exit(1)

if __name__ == "__main__":
    main()