#!/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:]):
    # hostname
    result = subprocess.run(["/bin/hostname"], capture_output=True, text=True)
    hostname = str(result.stdout)
    

    # timestamp
    result = subprocess.run(["/bin/date", "--utc", "+%D %T"], capture_output=True, text=True)
    datetime = str(result.stdout).split()
    date = datetime[0]
    timestamp = datetime[1]

    # vmstat
    result = subprocess.run(["/usr/bin/vmstat", "-s"], capture_output=True, text=True)

    # Translate vmstat(8)'s output to a dictionary.
    vmstat = dict()
    txt = str(result.stdout).splitlines()
    for line in txt:
        line = line.split()
        value = line[0]
        key = line[1]
        for k in range(2, len(line)):
            key = key + ' ' + line[k]
        vmstat[key] = value

    tag = 'hostname=' + hostname
    tag += ',date=' + date
    tag += ',timestamp=' + timestamp

    meas = 'mem=' + vmstat['K total memory']
    meas += ',swpd=' + vmstat['K used swap']
    meas += ',free=' + vmstat['K free memory']
    meas += ',buff=' + vmstat['K buffer memory']
    meas += ',cache=' + vmstat['K swap cache']
    meas += ',swapin=' + vmstat['pages swapped in']
    meas += ',swapout=' + vmstat['pages swapped out']

    append_msg('v1/mem', tag, meas)
    publish.multiple(msg)


if __name__ == "__main__":
    cli()

