#!/usr/bin/env python3
# 2021 created by Bastian Kuhn, bastian-kuhn.de
# 2021 reworked by Sven Rueß, sritd.de
"""
Cohesity Checks
"""
import argparse
import datetime
import json
import sys
from pathlib import Path

import requests
import urllib3

from cmk.utils import password_store

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


def parse_args():
    parser = argparse.ArgumentParser(description="Cohesity Special Agent for Checkmk")
    parser.add_argument("--host", required=True, help="Cluster VIP")
    parser.add_argument("--user", required=True, help="Username")
    parser.add_argument(
        "--password-id",
        required=True,
        help="Password store reference in the form '<pw_id>:<pw_file>'",
    )
    parser.add_argument("--domain", required=True, help="Auth domain (e.g. LOCAL)")
    parser.add_argument(
        "--verify-cert",
        required=True,
        choices=["True", "False"],
        help="Verify SSL certificate",
    )
    return parser.parse_args()


ARGS = parse_args()
PW_ID, PW_FILE = ARGS.password_id.split(":", 1)
PASSWORD = password_store.lookup(Path(PW_FILE), PW_ID)
VERIFY = ARGS.verify_cert == "True"
API_URL = f"https://{ARGS.host}/irisservices/api/v1"


def get_header():
    """
    Cluster Status
    """
    creds = json.dumps({
        "password": PASSWORD,
        "username": ARGS.user,
        "domain": ARGS.domain,
    })
    header = {
        "accept": "application/json",
        "content-type": "application/json",
    }
    url = API_URL + "/public/accessTokens"
    try:
        response = requests.post(url, data=creds, headers=header, verify=VERIFY)
    except OSError:
        print(f"Connection error to {url}")
        sys.exit(1)

    if response != "" and response.status_code == 201:
        access_token = response.json()["accessToken"]
        token_type = response.json()["tokenType"]
        header["authorization"] = token_type + " " + access_token
        return header

    print("Cannot get Token {}".format(response.json()))
    sys.exit(1)


HEADER = get_header()


def get_url(url):
    try:
        response = requests.get(
            API_URL + url,
            headers=HEADER,
            verify=VERIFY,
        )
    except OSError:
        print(f"Cannot get Clusterstatus from {API_URL}{url}")
        sys.exit(1)
    return response.json()


def get_cluster_status():
    response_json = get_url("/nexus/cluster/status")
    print("<<<cohesity_node_status>>>")
    for node in response_json["nodeStatus"]:
        failed_services = []
        ok_services = []
        if node["serviceStatus"]:
            for service in node["serviceStatus"]:
                service_name = service["name"]
                if len(service["processIds"]) >= 1:
                    ok_services.append(service_name)
                else:
                    failed_services.append(service_name)
        print("{} failed {}".format(node["hostname"], ",".join(failed_services)))
        print("{} ok {}".format(node["hostname"], ",".join(ok_services)))


def get_storage():
    """
    Get Storage Information
    """
    print("<<<cohesity_storage_usage>>>")
    for key, value in get_url("/public/stats/storage").items():
        print(f"{key} {value}")


def get_metadata():
    """
    Get Metadata Information
    """
    print("<<<cohesity_metadata_usage>>>")
    for key, value in get_url("/public/cluster").items():
        if not isinstance(value, (int, float)):
            continue
        print(f"{key} {value}")


def get_alerts():
    """
    Query API Alerts
    """
    time_to = int(datetime.datetime.now().timestamp() * 1_000_000)
    time_from = time_to - (86400 * 1_000_000)
    url = f"/public/stats/alerts?startTimeUsecs={time_from}&endTimeUsecs={time_to}"
    print("<<<cohesity_alerts>>>")
    for key, value in get_url(url).items():
        print(f"{key} {value}")


def get_unprotected_objects():
    """
    Get Unproteced Objects
    """
    url = "/public/stats/protectionSummary"
    print("<<<cohesity_unprotected>>>")
    for key, value in get_url(url).items():
        if key == "statsByEnv":
            continue
        print(f"{key} {value}")


if __name__ == "__main__":
    get_cluster_status()
    get_storage()
    get_metadata()
    get_alerts()
    get_unprotected_objects()
