#!/usr/bin/env python3
# verifyhash — verify files against a checksum file (sha256sum/md5sum/sha1sum/sha512sum format), auto-detecting the algorithm.
# Usage: verifyhash [--base DIR] manifest.txt
"""verifyhash: checksum verification that doesn't make you name the algorithm.
It infers md5/sha1/sha256/sha512 from the hex length, handles both `hash  file`
and `hash *file` forms, and reports OK / FAILED / MISSING with a summary —
plus it checks the manifest itself for duplicate entries."""
import argparse, hashlib, os, sys

ALGOS = {32: "md5", 40: "sha1", 64: "sha256", 128: "sha512"}

def parse_manifest(path):
    entries = []
    with open(path, errors="replace") as f:
        for ln, line in enumerate(f, 1):
            line = line.rstrip("\n")
            if not line.strip() or line.startswith("#"): continue
            parts = line.split(None, 1)
            if len(parts) < 2:
                print(f"verifyhash: {path}:{ln}: malformed line", file=sys.stderr); continue
            h, name = parts[0], parts[1].lstrip(" *")
            entries.append((h.lower(), name, ln))
    return entries

def verify(manifest, base="."):
    entries = parse_manifest(manifest)
    seen = {}
    ok = failed = missing = 0
    for h, name, ln in entries:
        if name in seen:
            print(f"DUPLICATE entry for {name} (lines {seen[name]} and {ln})")
        seen[name] = ln
        algo = ALGOS.get(len(h))
        if not algo:
            print(f"UNKNOWN hash length {len(h)} for {name}"); failed += 1; continue
        p = os.path.join(base, name)
        if not os.path.isfile(p):
            print(f"MISSING {name}"); missing += 1; continue
        d = hashlib.new(algo)
        with open(p, "rb") as f:
            for chunk in iter(lambda: f.read(65536), b""): d.update(chunk)
        if d.hexdigest() == h:
            print(f"OK {name} ({algo})"); ok += 1
        else:
            print(f"FAILED {name} ({algo}): expected {h[:16]}..., got {d.hexdigest()[:16]}..."); failed += 1
    print(f"verifyhash: {ok} OK, {failed} FAILED, {missing} MISSING, {len(entries)} entries")
    return 1 if (failed or missing) else 0

def selftest():
    import tempfile
    with tempfile.TemporaryDirectory() as d:
        a = os.path.join(d, "a.txt"); open(a, "w").write("hello\n")
        h = hashlib.sha256(open(a, "rb").read()).hexdigest()
        m = os.path.join(d, "SUMS"); open(m, "w").write(f"{h}  a.txt\n")
        assert verify(m, base=d) == 0
        open(a, "w").write("tampered\n")
        assert verify(m, base=d) == 1
    print("verifyhash selftest: PASS"); return 0

def main():
    ap = argparse.ArgumentParser(description="Verify files against a checksum manifest, auto-detecting md5/sha1/sha256/sha512.")
    ap.add_argument("manifest", nargs="?", help="checksum file in sha256sum format")
    ap.add_argument("--base", default=".", help="directory the manifest's paths are relative to")
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest: return selftest()
    if not a.manifest: ap.error("need a manifest file")
    return verify(a.manifest, a.base)

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