#!/usr/bin/env python3
# Copyright (C) 2019 Checkmk GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

# Example program for accessing status of event console

import ast
import os
import socket
from pathlib import Path

# Create Unix socket and connect to status socket
path = Path(os.getenv("OMD_ROOT", "/")) / "tmp/run/mkeventd/status"
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(str(path))

# Send query
sock.sendall(b"GET events\nFilter: event_phase = open")
sock.shutdown(socket.SHUT_WR)

# Read response and convert Python source to Python object
response_text = b""
while True:
    chunk = sock.recv(8192)
    response_text += chunk
    if not chunk:
        break
response = ast.literal_eval(response_text.decode("utf-8"))

# The name of the column headers are the first item of the result list
headers = response[0]

# Output all results
for row in response[1:]:
    with_headers = sorted(zip(headers, row))

    for key, value in with_headers:
        print("%-20s: %s" % (key, value))
    print()
