#!/usr/bin/env python3
# sshkeys - list SSH keys, their fingerprints, and which are loaded in the agent
# Usage: sshkeys [--dir DIR] [--agent]
import argparse, glob, os, subprocess, sys

def fingerprint(pub_path):
    r = subprocess.run(["ssh-keygen", "-lf", pub_path], capture_output=True, text=True)
    if r.returncode == 0:
        return r.stdout.strip()
    return None

def selftest():
    import tempfile
    with tempfile.TemporaryDirectory() as d:
        home = os.path.join(d, "home"); os.makedirs(os.path.join(home, ".ssh"))
        subprocess.run(["ssh-keygen", "-t", "ed25519", "-N", "", "-C", "selftest@test",
                        "-f", os.path.join(home, ".ssh", "id_ed25519")],
                       check=True, capture_output=True)
        env = dict(os.environ, HOME=home)
        out = subprocess.run([sys.executable, os.path.abspath(__file__), "--dir",
                              os.path.join(home, ".ssh")],
                             capture_output=True, text=True, env=env)
        assert out.returncode == 0, out.stderr
        assert "ed25519" in out.stdout.lower() and "selftest@test" in out.stdout, out.stdout
        print("sshkeys selftest: PASS")
    return 0

def main():
    ap = argparse.ArgumentParser(prog="sshkeys",
        description="List SSH keys, their fingerprints, and which are loaded in the agent.")
    ap.add_argument("--dir", default=os.path.expanduser("~/.ssh"),
                    help="SSH directory to scan (default ~/.ssh)")
    ap.add_argument("--agent", action="store_true", help="also show keys loaded in ssh-agent")
    ap.add_argument("--selftest", action="store_true", help="run built-in self-test and exit")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    loaded = set()
    if a.agent or True:
        r = subprocess.run(["ssh-add", "-l"], capture_output=True, text=True)
        if r.returncode == 0:
            for line in r.stdout.splitlines():
                parts = line.split()
                if len(parts) >= 2:
                    loaded.add(parts[1])
    pubs = sorted(glob.glob(os.path.join(a.dir, "*.pub")))
    if not pubs:
        print("sshkeys: no public keys found in %s" % a.dir)
        if loaded:
            print("agent holds %d key(s) with no matching .pub file:" % len(loaded))
            for fp in sorted(loaded):
                print("  %s" % fp)
        return 0
    print("SSH keys in %s:" % a.dir)
    for pub in pubs:
        priv = pub[:-4]
        info = fingerprint(pub) or "(unreadable key)"
        parts = info.split()
        fp = parts[1] if len(parts) >= 2 else ""
        kind = parts[3] if len(parts) >= 4 else ""
        comment = parts[2] if len(parts) >= 3 else ""
        exists = "private key present" if os.path.exists(priv) else "NO private key"
        mark = "LOADED in agent" if fp in loaded else "not in agent"
        print("  %s" % os.path.basename(pub))
        print("    type: %s  fingerprint: %s" % (kind, fp))
        print("    comment: %s | %s | %s" % (comment or "-", exists, mark))
    return 0

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