#!/usr/bin/env python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Mathias Kettner 2018             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, getopt
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning # pylint: disable=import-error
from HTMLParser import HTMLParser

def usage():
    sys.stderr.write("""Check_MK VMWare SRM

USAGE: agent_srm [OPTIONS] HOST

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

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

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


opt_demo = False
opt_cert = True
args_dict = {}
resources = []

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

class HTMLTableParser(HTMLParser):
    def __init__(
        self,
        decode_html_entities=False,
        data_separator=' ',
    ):

        HTMLParser.__init__(self)

        self._parse_html_entities = decode_html_entities
        self._data_separator = data_separator

        self._in_td = False
        self._in_th = False
        self._current_table = []
        self._current_row = []
        self._current_cell = []
        self.tables = []

    def handle_starttag(self, tag, attrs):
        if tag == 'td':
            self._in_td = True
        if tag == 'th':
            self._in_th = True

    def handle_data(self, data):
        if self._in_td or self._in_th:
            self._current_cell.append(data.strip())

    def handle_charref(self, name):

        if self._parse_html_entities:
            self.handle_data(self.unescape('&#{};'.format(name)))

    def handle_endtag(self, tag):
        if tag == 'td':
            self._in_td = False
        elif tag == 'th':
            self._in_th = False

        if tag in ['td', 'th']:
            final_cell = self._data_separator.join(self._current_cell).strip()
            self._current_row.append(final_cell)
            self._current_cell = []
        elif tag == 'tr':
            self._current_table.append(self._current_row)
            self._current_row = []
        elif tag == 'table':
            self.tables.append(self._current_table)
            self._current_table = []

parser=HTMLTableParser()

def query(url):
    if opt_cert == False:
        requests.packages.urllib3.disable_warnings(InsecureRequestWarning) # pylint: disable=no-member
    response     = requests.get(url, verify=opt_cert)
    raw_html     = response.text
    return raw_html
output_lines = []
def output(line):
    output_lines.append(line)

def query_srm():
    if opt_demo:
        return parser.feed(srm_status)
    url = "https://%(address)s:9086/" % args_dict
    return parser.feed(query(url))

def process_srm_info():
    output("<<<vcenter_srm:sep(9)>>>")
    query_srm()
    local_connection = parser.tables[0]
    remote_connection = parser.tables[1]
    i=2
    for row in local_connection:
        if str(row[0]) == "Service":
	    output("LocalConnection %s\t%s\t%s" % (row[1],local_connection[i][1],local_connection[i+2][1]))
	    i+=5

    i=2
    for row in remote_connection:
        if str(row[0]) == "Service":
            output("RemoteConnection %s\t%s\t%s" % (row[1],local_connection[i][1],remote_connection[i+2][1]))
            i+=5

def main():
    try:
        process_srm_info()
        sys.stdout.write("\n".join(output_lines) + "\n")
    except Exception, e:
        sys.stderr.write("Connection error: %s" % e)
        sys.exit(1)


srm_status = \
"""
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=windows-1252"><style></style></head><body><h3>VMware vCenter Site Recovery Manager 6.5.1.6014840</h3><p>Name: <b>buc01m01vc01.test</b>, UUID: <b>d8fd8aea-a3ed-46e9-857e-509b80784c53</b>, Extension key: <b>com.vmware.vcDr</b></p><h4>VMware vCenter Server 6.5.0 build-7515524</h4><hr><p><a href="https://buc01m01srm01.test:9086/vcdr/vmomi/drserviceversions.xml">Supported VMODL versions</a></p><p><a href="https://buc01m01srm01.test:9086/vcdr/vmomi/drversion.xml">Inherent VMODL version</a></p><hr><h4>Local Connections</h4><table><tbody><tr><td>--------------------</td><td>--------------------------------------------------------------------------------</td></tr><tr><td>Service</td><td>com.vmware.cis.vcenterserver</td></tr><tr><td>URL</td><td>https://buc01m01vc01.test:443/sdk</td></tr><tr><td>Thumbprint</td><td>unknown</td></tr><tr><td>Status</td><td style="color:#080;">Connected</td></tr><tr><td>--------------------</td><td>--------------------------------------------------------------------------------</td></tr><tr><td>Service</td><td>com.vmware.cis.cs.inventory</td></tr><tr><td>URL</td><td>https://buc01m01vc01.test:443/invsvc/vmomi/sdk</td></tr><tr><td>Thumbprint</td><td>unknown</td></tr><tr><td>Status</td><td style="color:#080;">Connected</td></tr><tr><td>--------------------</td><td>--------------------------------------------------------------------------------</td></tr><tr><td>Service</td><td>com.vmware.cis.cs.lookup</td></tr><tr><td>URL</td><td>https://buc01psc01.test:443/lookupservice/sdk</td></tr><tr><td>Thumbprint</td><td>unknown</td></tr><tr><td>Status</td><td style="color:#080;">Connected</td></tr><tr><td>--------------------</td><td>--------------------------------------------------------------------------------</td></tr><tr><td>Service</td><td>com.vmware.cis.cs.identity</td></tr><tr><td>URL</td><td>https://buc01psc01.test/sso-adminserver/sdk/vsphere.local</td></tr><tr><td>Thumbprint</td><td>unknown</td></tr><tr><td>Status</td><td style="color:#080;">Connected</td></tr><tr><td>--------------------</td><td>--------------------------------------------------------------------------------</td></tr><tr><td>Service</td><td>com.vmware.cis.cs.authorization</td></tr><tr><td>URL</td><td>https://buc01m01vc01.test:443/invsvc/vmomi/sdk</td></tr><tr><td>Thumbprint</td><td>unknown</td></tr><tr><td>Status</td><td style="color:#080;">Connected</td></tr><tr><td>--------------------</td><td>--------------------------------------------------------------------------------</td></tr><tr><td>Service</td><td>com.vmware.cis.cs.license</td></tr><tr><td>URL</td><td>https://buc01psc01.test:443/ls/sdk</td></tr><tr><td>Thumbprint</td><td>unknown</td></tr><tr><td>Status</td><td style="color:#080;">Connected</td></tr><tr><td>--------------------</td><td>--------------------------------------------------------------------------------</td></tr></tbody></table><h4>Paired with remote SRM with name 'clj01m01vc01.test' and uuid 'acf7df22-01bb-439a-b27e-9f8b83e23233'</h4><h4>Remote Connections</h4><table><tbody><tr><td>--------------------</td><td>--------------------------------------------------------------------------------</td></tr><tr><td>Service</td><td>com.vmware.cis.vcenterserver</td></tr><tr><td>URL</td><td>https://clj01m01vc01.test:443/sdk</td></tr><tr><td>Thumbprint</td><td>unknown</td></tr><tr><td>Status</td><td style="color:#080;">Connected</td></tr><tr><td>--------------------</td><td>--------------------------------------------------------------------------------</td></tr><tr><td>Service</td><td>com.vmware.dr.vcDr</td></tr><tr><td>URL</td><td>https://clj01m01srm01.test:9086/vcdr/vmomi/sdk</td></tr><tr><td>Thumbprint</td><td>unknown</td></tr><tr><td>Status</td><td style="color:#080;">Connected</td></tr><tr><td>--------------------</td><td>--------------------------------------------------------------------------------</td></tr><tr><td>Service</td><td>com.vmware.cis.cs.lookup</td></tr><tr><td>URL</td><td>https://clj01psc01.test:443/lookupservice/sdk</td></tr><tr><td>Thumbprint</td><td>unknown</td></tr><tr><td>Status</td><td style="color:#080;">Connected</td></tr><tr><td>--------------------</td><td>--------------------------------------------------------------------------------</td></tr><tr><td>Service</td><td>com.vmware.cis.cs.identity</td></tr><tr><td>URL</td><td>https://clj01psc01.test/sso-adminserver/sdk/vsphere.local</td></tr><tr><td>Thumbprint</td><td>unknown</td></tr><tr><td>Status</td><td style="color:#080;">Connected</td></tr><tr><td>--------------------</td><td>--------------------------------------------------------------------------------</td></tr></tbody></table></body></html>"""

if __name__ == "__main__":
    main()