#!/usr/bin/python3

import json
import paho.mqtt.publish as publish
import re
import subprocess
import sys

msg = list()

def append_msg(topic, tag, meas):
    global msg
    msg.append({'topic' : topic,
                'payload' : re.sub(r"[\n\t\s]*", "", tag)
                + ' ' + re.sub(r"[\n\t\s]*", "", meas)})


def cli(argv=sys.argv[1:]):
    result = subprocess.run(["/usr/bin/mpstat", "-A", "-o", "JSON"], capture_output=True, text=True)
    txt = str(result.stdout).split()
    txt = ' '.join(txt)

    j = json.loads(txt)
    host = j['sysstat']['hosts'][0]
    stats = host['statistics'][0]
    cpu_load = stats['cpu-load'][0]
    irqs = stats['sum-interrupts'][0]

    tag = 'hostname=' + host['nodename']
    tag += ',date=' + host['date']
    result = subprocess.run(["/bin/date", "--utc", "+%T"], capture_output=True, text=True)
    tag += ',timestamp=' + ' '.join(str(result.stdout).split())

    meas = 'usr=' + str(cpu_load['usr'])
    meas += ',nice=' + str(cpu_load['nice'])
    meas += ',sys=' + str(cpu_load['sys'])
    meas += ',iowait=' + str(cpu_load['iowait'])
    meas += ',irq=' + str(cpu_load['irq'])
    meas += ',soft=' + str(cpu_load['soft'])
    meas += ',steal=' + str(cpu_load['steal'])
    meas += ',guest=' + str(cpu_load['guest'])
    meas += ',gnice=' + str(cpu_load['gnice'])
    meas += ',idle=' + str(cpu_load['idle'])

    append_msg('v1/cpu', tag, meas)

    meas = 'sec=' + str(irqs['intr'])
    append_msg('v1/irq', tag, meas)

    publish.multiple(msg)


if __name__ == "__main__":
    cli()

