#!/usr/bin/python3

import argparse
import socket
import ssl
import time

import ltsdb_record

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()

now = time.time()
report0 = []

try:
    with socket.create_connection((args.hostname, args.port)) as sock:
        context = ssl.create_default_context()
        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, ConnectionRefusedError) 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
]

success = ltsdb_record.record_observations(report)
exit(1 - success)