#!/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/iostat", "-d", "-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]
    disk = stats['disk'][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())
    tag += ',device=' + str(disk['disk_device'])

    meas = 'tps=' + str(disk['tps'])
    meas += ',kB_reads=' + str(disk['kB_read/s'])
    meas += ',kB_wrtns=' + str(disk['kB_wrtn/s'])
    meas += ',kB_read=' + str(disk['kB_read'])
    meas += ',kB_wrtn=' + str(disk['kB_wrtn'])

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

    publish.multiple(msg)


if __name__ == "__main__":
    cli()

