#!/usr/bin/env python3
"""backupcheck - verify a backup tree matches its source by hash, report missing/changed.
Usage: backupcheck SOURCE BACKUP [--quick] [--selftest]
Walks both trees by relative path and reports files missing from the backup,
files changed (hash, or size+mtime with --quick), and extra files that exist
only in the backup."""
import argparse, hashlib, os, sys

def human(n):
    for u in ("B", "K", "M", "G", "T"):
        if abs(n) < 1024 or u == "T":
            return f"{n:.1f}{u}" if u != "B" else f"{int(n)}B"
        n /= 1024.0
    return f"{n:.1f}T"

def sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        while True:
            b = f.read(1024 * 1024)
            if not b:
                break
            h.update(b)
    return h.hexdigest()

def inventory(root):
    inv = {}
    for cur, _dirs, files in os.walk(root):
        for name in files:
            p = os.path.join(cur, name)
            rel = os.path.relpath(p, root)
            try:
                st = os.lstat(p)
            except OSError:
                continue
            inv[rel] = (st.st_size, int(st.st_mtime))
    return inv

def compare(src, dst, quick=False):
    s_inv = inventory(src)
    d_inv = inventory(dst)
    missing, changed, extra = [], [], []
    for rel, (sz, mt) in s_inv.items():
        if rel not in d_inv:
            missing.append((rel, sz))
        else:
            dsz, dmt = d_inv[rel]
            if quick:
                if dsz != sz or dmt != mt:
                    changed.append((rel, sz, dsz))
            else:
                if dsz != sz:
                    changed.append((rel, sz, dsz))
                else:
                    try:
                        if sha256(os.path.join(src, rel)) != sha256(os.path.join(dst, rel)):
                            changed.append((rel, sz, dsz))
                    except OSError:
                        changed.append((rel, sz, dsz))
    for rel, (sz, _mt) in d_inv.items():
        if rel not in s_inv:
            extra.append((rel, sz))
    return {"missing": missing, "changed": changed, "extra": extra,
            "src_files": len(s_inv), "dst_files": len(d_inv)}

def selftest():
    import tempfile
    tmp = tempfile.mkdtemp(prefix="backupcheck-test-")
    src, dst = os.path.join(tmp, "src"), os.path.join(tmp, "dst")
    os.makedirs(src); os.makedirs(dst)
    def w(d, name, content):
        with open(os.path.join(d, name), "wb") as f:
            f.write(content)
    w(src, "same.txt", b"same")
    w(dst, "same.txt", b"same")
    w(src, "changed.txt", b"version two")
    w(dst, "changed.txt", b"version one")
    w(src, "missing.txt", b"not backed up")
    w(dst, "extra.txt", b"only in backup")
    r = compare(src, dst)
    ok = True
    if [m[0] for m in r["missing"]] != ["missing.txt"]:
        print(f"FAIL: missing={r['missing']}"); ok = False
    if [c[0] for c in r["changed"]] != ["changed.txt"]:
        print(f"FAIL: changed={r['changed']}"); ok = False
    if [e[0] for e in r["extra"]] != ["extra.txt"]:
        print(f"FAIL: extra={r['extra']}"); ok = False
    # same-size, different-content change must still be caught by hashing
    w(src, "sneaky.txt", b"aaaa")
    w(dst, "sneaky.txt", b"bbbb")
    r2 = compare(src, dst)
    if "sneaky.txt" not in [c[0] for c in r2["changed"]]:
        print("FAIL: same-size content change missed by hash"); ok = False
    import shutil; shutil.rmtree(tmp, ignore_errors=True)
    if ok:
        print("selftest: PASS (missing/changed/extra + same-size hash change all detected)")
    return 0 if ok else 1

def main():
    ap = argparse.ArgumentParser(prog="backupcheck",
        description="Verify a backup tree matches its source by hash, report missing/changed.")
    ap.add_argument("source", nargs="?", help="source tree")
    ap.add_argument("backup", nargs="?", help="backup tree to verify")
    ap.add_argument("--quick", action="store_true", help="compare size+mtime only, skip hashing")
    ap.add_argument("--selftest", action="store_true", help="run built-in checks on temp trees")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    if not a.source or not a.backup:
        ap.error("SOURCE and BACKUP are required")
    if not os.path.isdir(a.source) or not os.path.isdir(a.backup):
        print("error: both SOURCE and BACKUP must be directories", file=sys.stderr)
        return 2
    r = compare(a.source, a.backup, a.quick)
    print(f"source: {r['src_files']} files   backup: {r['dst_files']} files")
    if r["missing"]:
        print(f"\nMISSING from backup ({len(r['missing'])}):")
        for rel, sz in sorted(r["missing"])[:20]:
            print(f"  {human(sz):>10}  {rel}")
    if r["changed"]:
        print(f"\nCHANGED ({len(r['changed'])}):")
        for rel, ssz, dsz in sorted(r["changed"])[:20]:
            print(f"  {human(ssz):>10} -> {human(dsz):>10}  {rel}")
    if r["extra"]:
        print(f"\nEXTRA in backup ({len(r['extra'])}):")
        for rel, sz in sorted(r["extra"])[:20]:
            print(f"  {human(sz):>10}  {rel}")
    if not (r["missing"] or r["changed"] or r["extra"]):
        print("backup matches source exactly.")
        return 0
    print(f"\nverdict: NOT IN SYNC - {len(r['missing'])} missing, "
          f"{len(r['changed'])} changed, {len(r['extra'])} extra")
    return 1

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