#!/usr/bin/env python3
# sshhost - known-hosts report with fingerprints
# Usage: sshhost [--file FILE]... [--check HOST] [--hashed]
import argparse, base64, hashlib, os, subprocess, sys

def fp_of_keyblob(b64):
    try:
        raw = base64.b64decode(b64)
    except Exception:
        return "(bad base64)"
    return "SHA256:" + base64.b64encode(hashlib.sha256(raw).digest()).decode().rstrip("=")

def parse_known_hosts(path):
    entries = []
    try:
        lines = open(path, errors="replace").read().splitlines()
    except OSError as e:
        print("sshhost: cannot read %s: %s" % (path, e), file=sys.stderr)
        return entries
    for ln, line in enumerate(lines, 1):
        if not line.strip() or line.startswith("#"):
            continue
        parts = line.split()
        if len(parts) < 3:
            entries.append((ln, "(unparsable)", "", "(bad line)")); continue
        hosts, keytype, keyblob = parts[0], parts[1], parts[2]
        if hosts.startswith("|1|"):
            hosts = "(hashed)"
        entries.append((ln, hosts, keytype, fp_of_keyblob(keyblob)))
    return entries

def selftest():
    import tempfile
    with tempfile.TemporaryDirectory() as d:
        subprocess.run(["ssh-keygen", "-t", "ed25519", "-N", "", "-C", "hostkey",
                        "-f", os.path.join(d, "hostkey")], check=True, capture_output=True)
        pub = open(os.path.join(d, "hostkey.pub")).read().split()
        kh = os.path.join(d, "known_hosts")
        with open(kh, "w") as f:
            f.write("example.com,192.0.2.1 %s %s\n" % (pub[0], pub[1]))
        out = subprocess.run([sys.executable, os.path.abspath(__file__), "--file", kh],
                             capture_output=True, text=True)
        assert out.returncode == 0, out.stderr
        assert "example.com" in out.stdout and "SHA256:" in out.stdout, out.stdout
        assert pub[0] in out.stdout
        print("sshhost selftest: PASS")
    return 0

def main():
    ap = argparse.ArgumentParser(prog="sshhost",
        description="Known-hosts report: every host, key type and fingerprint.")
    ap.add_argument("--file", action="append", default=[],
                    help="known_hosts file (default ~/.ssh/known_hosts; repeatable)")
    ap.add_argument("--check", help="check whether HOST is in known_hosts (exit 0 if found)")
    ap.add_argument("--hashed", action="store_true", help="only show hashed host entries")
    ap.add_argument("--selftest", action="store_true", help="run built-in self-test and exit")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    files = a.file or [os.path.expanduser("~/.ssh/known_hosts")]
    all_entries = []
    for path in files:
        for ln, hosts, keytype, fp in parse_known_hosts(path):
            all_entries.append((path, ln, hosts, keytype, fp))
    if a.check:
        for _p, _ln, hosts, _kt, _fp in all_entries:
            if a.check in hosts.split(","):
                print("%s is known." % a.check); return 0
        # also ask ssh-keygen, which understands hashed entries
        r = subprocess.run(["ssh-keygen", "-F", a.check, "-f", files[0]],
                           capture_output=True, text=True)
        if r.returncode == 0:
            print("%s is known (hashed entry)." % a.check); return 0
        print("%s is NOT in known_hosts." % a.check); return 1
    if not all_entries:
        print("sshhost: no known-host entries found."); return 0
    print("known hosts (%d entr%s):" % (len(all_entries), "y" if len(all_entries) == 1 else "ies"))
    for path, ln, hosts, keytype, fp in all_entries:
        if a.hashed and hosts != "(hashed)":
            continue
        print("  %-40s %-12s %s   [%s:%d]" % (hosts, keytype, fp, os.path.basename(path), ln))
    return 0

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