#!/usr/bin/env python3
# zipcheck — verify archive integrity (zip CRC + tar readability) and report the broken ones.
# Usage: zipcheck [--recursive] [directory-or-archive ...]
"""zipcheck: integrity sweep for archives. It CRC-checks every zip member
(testzip) and fully reads every tarball, then reports OK vs BROKEN per file
with the failing member named — a batch `unzip -t` that also covers tar."""
import argparse, os, sys, tarfile, zipfile

ARCH_EXTS = (".zip", ".tar", ".tar.gz", ".tgz", ".tar.bz2", ".tar.xz", ".jar", ".whl")

def check(path):
    """Return (ok, detail)."""
    try:
        if path.lower().endswith((".zip", ".jar", ".whl")):
            with zipfile.ZipFile(path) as z:
                bad = z.testzip()
                if bad is not None:
                    return False, f"member {bad} failed CRC"
                # also force-read every member (testzip only CRCs via read)
                for i in z.infolist():
                    z.read(i.filename)
            return True, f"{len(z.infolist())} members OK"
        with tarfile.open(path, "r:*") as t:
            n = 0
            for m in t:
                if m.isfile():
                    f = t.extractfile(m)
                    if f:
                        while f.read(65536): pass
                    n += 1
            return True, f"{n} files read OK"
    except Exception as e:
        return False, str(e)

def collect(targets, recursive):
    paths = []
    for t in targets:
        if os.path.isdir(t):
            for root, dirs, files in os.walk(t):
                for f in files:
                    if f.lower().endswith(ARCH_EXTS): paths.append(os.path.join(root, f))
                if not recursive: break
        elif os.path.isfile(t):
            paths.append(t)
    return sorted(paths)

def selftest():
    import tempfile, zipfile
    with tempfile.TemporaryDirectory() as d:
        good = os.path.join(d, "good.zip")
        with zipfile.ZipFile(good, "w", zipfile.ZIP_DEFLATED) as z:
            z.writestr("a.txt", "data" * 100)
        bad = os.path.join(d, "bad.zip")
        with open(bad, "wb") as f: f.write(b"PK\x03\x04" + b"\x00" * 100)
        ok, _ = check(good); assert ok
        ok2, _ = check(bad); assert not ok2
    print("zipcheck selftest: PASS"); return 0

def main():
    ap = argparse.ArgumentParser(description="Verify integrity of zip/tar archives; report the broken ones.")
    ap.add_argument("targets", nargs="*", default=["."], help="archive files or directories to scan")
    ap.add_argument("--recursive", "-r", action="store_true")
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest: return selftest()
    paths = collect(a.targets, a.recursive)
    if not paths: print("no archives found"); return 0
    bad = 0
    for p in paths:
        ok, detail = check(p)
        print(f"{'OK    ' if ok else 'BROKEN'} {p}  ({detail})")
        bad += not ok
    print(f"{len(paths)-bad}/{len(paths)} OK, {bad} broken")
    return 1 if bad else 0

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