#!/usr/bin/python3

import argparse
import hmac
import json
import os
import pprint
import random
import socket
import subprocess
import time

import requests

ap = argparse.ArgumentParser()
ap.add_argument("directory")
args = ap.parse_args()

# It's a bit weird that this works.
hostname = socket.gethostbyaddr(socket.gethostname())[0]


now = time.time()
p = subprocess.run(["/usr/bin/dus", args.directory], capture_output=True, text=True)
report = []
for ln in p.stdout.split("\n")[:-1]:
    (size, directory) = ln.split("\t")

    report.append(
        {
            "description": {
                "hostname": hostname,
                "directory": directory,
                "measure": "diskusage",
                "unit": "bytes",
            },
            "data": [
                [now, int(size)*1024]
            ]
        }
    )
for dir in (".", os.environ["HOME"] + "/.config/ltsdb", "/etc/ltsdb"):
    try:
        with open(dir + "/config.json") as fh:
            client_config = json.load(fh)
        baseurl = client_config["server"]
        break
    except FileNotFoundError:
        pass
while True:
    for r in report:
        node = hostname
        timestamp = time.time()
        msg = (node + " " + str(timestamp)).encode("UTF-8")
        digest = hmac.new(client_config["key"].encode("UTF-8"), msg, "SHA256").hexdigest()
        r["auth"] = {
            "node": node,
            "timestamp": timestamp,
            "hmac": digest,
        }
    #pprint.pp(report)
    r = requests.post(baseurl + "report", json=report)
    print(r)
    if r.status_code == 200:
        exit(0)
    elif r.status_code == 409:
        time.sleep(0.5 + random.random())
        continue
    else:
        exit(1)