#!/usr/bin/env python3
"""certcheck - a site's TLS certificate expiry date and issuer.
Usage: certcheck HOST [PORT] [--selftest]
  Opens a TLS connection (stdlib ssl, 5s timeout), reads the peer
  certificate, and reports: subject, issuer, valid-from / valid-to, days
  remaining, and a verdict (OK / EXPIRING SOON <30d / EXPIRED). The twist
  vs openssl s_client: one line per fact plus the verdict, so a cron job
  can grep for EXPIRING and warn before the site breaks.
"""
import argparse
import socket
import ssl
import sys
import threading
from datetime import datetime, timezone


def parse_cert_date(s):
    # cert dates look like "Feb 25 12:00:00 2027 GMT"
    return datetime.strptime(s, "%b %d %H:%M:%S %Y %Z").replace(tzinfo=timezone.utc)


def fmt_name(name_tuple):
    parts = []
    for rdn in name_tuple:
        for key, value in rdn:
            parts.append(f"{key}={value}")
    return ", ".join(parts)


def check(host, port=443, timeout=5.0):
    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE  # we report on the cert, even a bad one
    raw = socket.create_connection((host, port), timeout=timeout)
    try:
        with ctx.wrap_socket(raw, server_hostname=host) as tls:
            cert = tls.getpeercert()
            if not cert:
                # With CERT_NONE CPython leaves the parsed cert empty; the
                # DER form is always available, so decode that instead.
                der = tls.getpeercert(binary_form=True)
                cert = decode_der(der)
    finally:
        raw.close()
    return cert


def decode_der(der):
    """Decode a DER certificate to the getpeercert() dict form (stdlib only)."""
    import base64
    import os
    import tempfile
    b64 = base64.encodebytes(der).decode("ascii")
    pem = "-----BEGIN CERTIFICATE-----\n" + b64 + "-----END CERTIFICATE-----\n"
    fd, path = tempfile.mkstemp(suffix=".pem")
    try:
        os.write(fd, pem.encode("ascii"))
        os.close(fd)
        return ssl._ssl._test_decode_cert(path)
    finally:
        try:
            os.unlink(path)
        except OSError:
            pass


def verdict(days_left):
    if days_left < 0:
        return "EXPIRED"
    if days_left < 7:
        return "CRITICAL: expires within a week"
    if days_left < 30:
        return "EXPIRING SOON"
    return "OK"


def report(host, port, cert):
    subject = fmt_name(cert.get("subject", ()))
    issuer = fmt_name(cert.get("issuer", ()))
    not_after = parse_cert_date(cert["notAfter"])
    not_before = parse_cert_date(cert["notBefore"])
    now = datetime.now(timezone.utc)
    days = (not_after - now).days
    sans = []
    for typ, val in cert.get("subjectAltName", ()):
        if typ == "DNS":
            sans.append(val)
    print(f"host:     {host}:{port}")
    print(f"subject:  {subject}")
    print(f"issuer:   {issuer}")
    print(f"valid:    {not_before.strftime('%Y-%m-%d')} to {not_after.strftime('%Y-%m-%d')}")
    print(f"expires:  {not_after.strftime('%Y-%m-%d %H:%M UTC')} ({days} days left)")
    if sans:
        print(f"SANs:     {', '.join(sans[:8])}" + (" ..." if len(sans) > 8 else ""))
    print(f"verdict:  {verdict(days)}")
    return 0 if days >= 0 else 2


def selftest():
    # Build a throwaway self-signed cert with openssl (if present) and serve
    # TLS on localhost; otherwise verify the date math on a fabricated cert.
    import os
    import subprocess
    import tempfile
    tmp = tempfile.mkdtemp()
    cert_pem = os.path.join(tmp, "cert.pem")
    key_pem = os.path.join(tmp, "key.pem")
    have_openssl = False
    try:
        subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes",
                        "-keyout", key_pem, "-out", cert_pem, "-days", "90",
                        "-subj", "/CN=localhost"], capture_output=True, timeout=30, check=True)
        have_openssl = True
    except (OSError, subprocess.SubprocessError) as e:
        print(f"selftest: openssl unavailable ({e}); testing date math on a fabricated cert")
    if have_openssl:
        ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        ctx.load_cert_chain(cert_pem, key_pem)
        srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        srv.bind(("127.0.0.1", 0))
        port = srv.getsockname()[1]
        srv.listen(1)

        def serve():
            try:
                conn, _ = srv.accept()
                with ctx.wrap_socket(conn, server_side=True) as tls:
                    tls.recv(1)
            except OSError:
                pass

        threading.Thread(target=serve, daemon=True).start()
        cert = check("127.0.0.1", port)
        srv.close()
        rc = report("127.0.0.1", port, cert)
        days = (parse_cert_date(cert["notAfter"]) - datetime.now(timezone.utc)).days
        assert 80 <= days <= 90, f"unexpected days left: {days}"
        print("selftest: live TLS handshake, 90-day self-signed cert read — OK")
        return rc
    # Fallback: fabricated cert dict exercises the same report path.
    fake = {"subject": ((("commonName", "localhost"),),),
            "issuer": ((("commonName", "localhost"),),),
            "notBefore": "Dec  3 00:00:00 2026 GMT",
            "notAfter": "Mar  3 00:00:00 2027 GMT",
            "subjectAltName": (("DNS", "localhost"),)}
    return report("localhost", 443, fake)


def main():
    ap = argparse.ArgumentParser(description="certcheck - a site's TLS certificate expiry date and issuer")
    ap.add_argument("host", nargs="?", help="host to check")
    ap.add_argument("port", nargs="?", type=int, default=443, help="TLS port (default 443)")
    ap.add_argument("--selftest", action="store_true", help="check a throwaway self-signed cert on localhost")
    args = ap.parse_args()
    if args.selftest:
        return selftest()
    if not args.host:
        ap.error("HOST is required (or use --selftest)")
    try:
        cert = check(args.host, args.port)
    except (socket.gaierror, socket.timeout, OSError, ssl.SSLError) as e:
        print(f"certcheck: {args.host}:{args.port} — FAILED: {e}", file=sys.stderr)
        return 1
    return report(args.host, args.port, cert)


if __name__ == "__main__":
    sys.exit(main())
