#!/usr/bin/python3

import argparse
import hmac
import json
import os
import socket
import ssl
import time

import requests

ap = argparse.ArgumentParser()
ap.add_argument("--verbose", action="store_true")
ap.add_argument("hostname")
ap.add_argument("port", type=int, default=443, nargs="?")
args = ap.parse_args()

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

now = time.time()
report0 = []

with socket.create_connection((args.hostname, args.port)) as sock:
    context = ssl.create_default_context()
    try:
        with context.wrap_socket(sock, server_hostname=args.hostname) as ssock:
            cert = ssock.getpeercert()
            not_after = ssl.cert_time_to_seconds(cert["notAfter"])
            delta = not_after - now
    except ssl.SSLCertVerificationError as e:
        print("got error %s; setting delta to 0", e)
        delta = 0
    report0.append({ "measure": "tls_cert_ttl", "unit": "s", "value": delta })

report = [
    {
        "description": {
            "hostname": args.hostname,
            "port": args.port,
            "measure": r["measure"],
            "unit": r["unit"]
        },
        "data": [
            [now, r["value"]]
        ]
    }
    for r in report0
]

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 = myhostname
        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)