#!/usr/bin/env python3
"""G3 report signatures: hybrid post-quantum signing for customer-facing documents (2026-12-04).

Every signed file gets a small companion file  <name>.g3sig  holding TWO signatures over
the exact file bytes:
  ML-DSA-65  (NIST FIPS 204, post-quantum: a future quantum computer cannot forge it)
  Ed25519    (classic, widely supported today)
A document counts as GENUINE only if BOTH signatures verify (hybrid: safe if either holds).
Uses only the system `openssl` (3.5+ for ML-DSA). No homemade crypto.

  g3_report_sign.py sign FILE [FILE...]    -> FILE.g3sig
  g3_report_sign.py verify FILE [SIG]      -> GENUINE / NOT GENUINE  (exit 0 / 1)
  g3_report_sign.py export DIR             -> public keys + fingerprints + verify script for customers
  g3_report_sign.py keyinfo                -> fingerprints of our public keys

Private keys: ~/.config/g3/sign/*.key.pem (0600, created on first use).
Verifying needs only the PUBLIC keys: ~/.config/g3/sign/*.pub.pem, or --pubdir DIR.
"""
import base64, datetime, hashlib, json, os, shutil, subprocess, sys, tempfile
from pathlib import Path

KDIR = Path.home() / ".config" / "g3" / "sign"
ALGS = {"mldsa65": "ML-DSA-65", "ed25519": "ED25519"}
SIGNER = "G3 Software Solutions LLC (G3SSLLC), Ruthven, Iowa - g3ssllc.com"
VERIFY_URL = "https://g3ssllc.com/trust"


def _ossl(args, inp=None):
    p = subprocess.run(["openssl"] + args, input=inp, capture_output=True)
    return p.returncode, p.stdout, p.stderr.decode("utf-8", "replace")


def _paths(name, pubdir=None):
    d = Path(pubdir) if pubdir else KDIR
    return KDIR / f"g3-reports-{name}.key.pem", d / f"g3-reports-{name}.pub.pem"


def ensure_keys():
    KDIR.mkdir(parents=True, exist_ok=True); os.chmod(KDIR, 0o700)
    for name, alg in ALGS.items():
        sk, pk = _paths(name)
        if not sk.exists():
            old = os.umask(0o077)
            try:
                rc, _, err = _ossl(["genpkey", "-algorithm", alg, "-out", str(sk)])
            finally:
                os.umask(old)
            if rc:
                sys.exit(f"could not create {alg} key: {err[:200]}")
            os.chmod(sk, 0o600)
        if not pk.exists():
            rc, _, err = _ossl(["pkey", "-in", str(sk), "-pubout", "-out", str(pk)])
            if rc:
                sys.exit(f"could not export {alg} public key: {err[:200]}")


def key_id(pub_pem: Path) -> str:
    rc, der, _ = _ossl(["pkey", "-pubin", "-in", str(pub_pem), "-outform", "DER"])
    return hashlib.sha256(der).hexdigest()[:32] if rc == 0 else ""


def sign(path: Path) -> Path:
    ensure_keys()
    data = path.read_bytes()
    out = {"format": "g3sig-v1", "signer": SIGNER, "file": path.name, "size": len(data),
           "sha256": hashlib.sha256(data).hexdigest(),
           "signed_utc": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
           "verify_at": VERIFY_URL, "signatures": {}}
    with tempfile.TemporaryDirectory() as td:
        for name, alg in ALGS.items():
            sk, pk = _paths(name)
            sigf = Path(td) / f"{name}.sig"
            rc, _, err = _ossl(["pkeyutl", "-sign", "-rawin", "-inkey", str(sk), "-in", str(path), "-out", str(sigf)])
            if rc:
                sys.exit(f"{alg} signing failed: {err[:200]}")
            out["signatures"][name] = {"alg": alg, "key_id": key_id(pk),
                                       "sig_b64": base64.b64encode(sigf.read_bytes()).decode()}
    sp = path.with_name(path.name + ".g3sig")
    sp.write_text(json.dumps(out, indent=1))
    return sp


def verify(path: Path, sigp: Path = None, pubdir=None):
    """Return (genuine: bool, lines: list[str])."""
    sigp = sigp or path.with_name(path.name + ".g3sig")
    lines = []
    try:
        meta = json.loads(sigp.read_text())
    except Exception as e:
        return False, [f"cannot read signature file {sigp.name}: {e}"]
    if meta.get("format") != "g3sig-v1":
        return False, ["unknown signature format"]
    data = path.read_bytes()
    if hashlib.sha256(data).hexdigest() != meta.get("sha256"):
        lines.append("file CONTENT CHANGED since it was signed (fingerprint differs)")
    ok_all = True
    with tempfile.TemporaryDirectory() as td:
        for name, alg in ALGS.items():
            s = (meta.get("signatures") or {}).get(name)
            _, pk = _paths(name, pubdir)
            if not s:
                lines.append(f"{alg}: MISSING"); ok_all = False; continue
            if not pk.exists():
                lines.append(f"{alg}: public key not found ({pk})"); ok_all = False; continue
            if s.get("key_id") != key_id(pk):
                lines.append(f"{alg}: signed by a DIFFERENT key than G3's published key"); ok_all = False; continue
            sigf = Path(td) / f"{name}.sig"
            try:
                sigf.write_bytes(base64.b64decode(s.get("sig_b64", ""), validate=True))
            except Exception:
                lines.append(f"{alg}: signature is corrupted"); ok_all = False; continue
            rc, _, _ = _ossl(["pkeyutl", "-verify", "-rawin", "-pubin", "-inkey", str(pk), "-in", str(path), "-sigfile", str(sigf)])
            lines.append(f"{alg}: {'valid' if rc == 0 else 'INVALID'}")
            ok_all = ok_all and rc == 0
    genuine = ok_all and not any("CHANGED" in l for l in lines)
    lines.insert(0, f"signed by: {meta.get('signer')}  at {meta.get('signed_utc')}")
    return genuine, lines


def export(dirpath: Path):
    ensure_keys()
    dirpath.mkdir(parents=True, exist_ok=True)
    fp = []
    for name in ALGS:
        _, pk = _paths(name)
        shutil.copy2(pk, dirpath / pk.name)
        fp.append(f"{ALGS[name]:10} key id {key_id(pk)}")
    shutil.copy2(Path(__file__), dirpath / "g3_report_sign.py")
    (dirpath / "README.txt").write_text(
        "How to check that a G3SSLLC document is genuine\n"
        "================================================\n\n"
        "Every report we send comes with a companion file ending in .g3sig.\n"
        "It holds two signatures: ML-DSA-65 (post-quantum, NIST FIPS 204) and Ed25519.\n\n"
        "Needs: python3 and OpenSSL 3.5 or newer (Linux, or macOS with Homebrew openssl).\n\n"
        "  python3 g3_report_sign.py verify --pubdir . report.pdf\n\n"
        "GENUINE means: the file is exactly what G3SSLLC signed, byte for byte.\n\n"
        "Our public key fingerprints (also published at " + VERIFY_URL + "):\n  " + "\n  ".join(fp) + "\n")
    return fp


def main(argv):
    if not argv or argv[0] in ("-h", "--help"):
        print(__doc__); return 0
    if shutil.which("openssl") is None:
        print("openssl not found"); return 2
    cmd, rest = argv[0], argv[1:]
    pubdir = None
    if "--pubdir" in rest:
        i = rest.index("--pubdir"); pubdir = rest[i + 1]; rest = rest[:i] + rest[i + 2:]
    if cmd == "sign":
        for f in rest:
            print("signed:", sign(Path(f)))
        return 0
    if cmd == "verify":
        g, lines = verify(Path(rest[0]), Path(rest[1]) if len(rest) > 1 else None, pubdir)
        for l in lines:
            print("  " + l)
        print("GENUINE - this is the exact document G3SSLLC signed." if g else "NOT GENUINE - do not trust this document.")
        return 0 if g else 1
    if cmd == "export":
        for l in export(Path(rest[0])):
            print(l)
        print("exported to", rest[0]); return 0
    if cmd == "keyinfo":
        ensure_keys()
        for name in ALGS:
            print(f"{ALGS[name]:10} {key_id(_paths(name)[1])}")
        return 0
    print(__doc__); return 2


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
