#!/usr/bin/env python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# |             ____ _               _        __  __ _  __           |
# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
# |                                                                  |
# | Copyright Mathias Kettner 2016             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 sys, getopt, requests
try:
    import simplejson as json
except:
    import json

#   .--Arguments-----------------------------------------------------------.
#   |           _                                         _                |
#   |          / \   _ __ __ _ _   _ _ __ ___   ___ _ __ | |_ ___          |
#   |         / _ \ | '__/ _` | | | | '_ ` _ \ / _ \ '_ \| __/ __|         |
#   |        / ___ \| | | (_| | |_| | | | | | |  __/ | | | |_\__ \         |
#   |       /_/   \_\_|  \__, |\__,_|_| |_| |_|\___|_| |_|\__|___/         |
#   |                    |___/                                             |
#   +----------------------------------------------------------------------+
#   |                                                                      |
#   '----------------------------------------------------------------------'
def usage():
    sys.stderr.write("""Check_MK 3par Agent
USAGE: agent_3par [OPTIONS] HOST
       agent_3par -h

ARGUMENTS:
  HOST                                      Host name or IP address of 3par system

OPTIONS:
  -h, --help                                Show this help message and exit
  -u USER, --user USER                      Username for 3par login
  -p PASSWORD, --password PASSWORD          Password for 3par login
  -v VALUE,VALUE, --values VALUE,VALUE      Values to fetch from 3par system.
                                            Possible values:    system
                                                                hosts
                                                                ports
                                                                flashcache
                                                                volumes
                                                                cpgs
""")

opt_host = None
opt_user = None
opt_pass = None
opt_values = ["system", "cpgs", "volumes", "hosts", "capacity", "ports"]

short_options = "hh:u:p:v:"
long_options = [ "help", "user=", "password=", "values=" ]

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)

for opt, arg in opts:
        if opt in ['-h', '--help']:
            usage()
            sys.exit(0)
        elif opt in ["-u", "--user"]:
            opt_user = arg
        elif opt in ["-p", "--password"]:
            opt_password = arg
        elif opt in ["-v", "--values"]:
            opt_values = arg.split(",")
        elif not opt:
            usage()
            sys.exit(0)

if len(args) == 1:
    opt_host = args[0]
elif not args:
    sys.stderr.write("ERROR: No host given.\n")
    sys.exit(1)
else:
    sys.stderr.write("ERROR: Please specify exactly one host.\n")
    sys.exit(1)
#.-

url = "https://%s:8080/api/v1" % opt_host
headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
}
verify = False

# Initiate connection and get session Key. The api expects the login data
# in json format. The standard port for all requests is 8080 as it is hard
# coded above. Maybe this will be changed later!
try:
    req = requests.post("%s/credentials" % url,
                        json={'user':opt_user,'password':opt_password},
                        headers=headers,
                        timeout=10,
                        verify=verify)

except requests.exceptions.RequestException as e:
    sys.stderr.write("Error: {}".format(e))
    sys.exit(1)

# Status code should be 201.
if not req.status_code == requests.codes.CREATED:
    sys.stderr.write("Wrong status code: %s. Expected: %s \n" % (req.status_code,
                                                               requests.codes.CREATED))
    sys.exit(1)
else:
    try:
        # As Response we get the key also in json format. We just need the
        # key in our header for all further requests on the api.
        data = json.loads(req.text)
        headers["X-HP3PAR-WSAPI-SessionKey"] = data["key"]
    except:
        raise Exception("No session key received")

# Get the requested data. We put every needed value into an extra section
# to get better performance in the checkplugin if less data is needed.

for value in opt_values:
    print "<<<3par_%s:sep(0)>>>" % value
    req = requests.get("%s/%s" % (url, value),
                       headers=headers,
                       timeout=10,
                       verify=verify)
    value_data = req.text.replace("\r\n", "").replace("\n", "").replace(" ","")
    print value_data

# Perform a proper disconnect. The Connection is closed if the session key
# is deleted. The standard timeout for a session would be 15 minutes.
req = requests.delete("%s/credentials/%s" % (url, headers["X-HP3PAR-WSAPI-SessionKey"]),
                      headers=headers,
                      timeout=10,
                      verify=verify)

if not req.status_code == requests.codes.OK:
    sys.stderr.write("Wrong status code: %s. Expected: %s \n" % (req.status_code,
                                                               requests.codes.OK))
    sys.exit(1)
