#!/usr/bin/env python3
"""copysafe - copy a tree with post-copy hash verification and resume on interruption.
Usage: copysafe <src> <dest> [--resume] [--selftest] [--help]
Copies a tree file by file, SHA-256-verifying every file after it lands, and
writes a progress journal (<dest>/.copysafe-journal.json) recording each
verified file. If interrupted, re-run with --resume: already-verified files
are skipped (re-checked by size+mtime first, hash only on doubt), so a
10 GB copy that died at 90% resumes instead of restarting. Mismatches are
retried once, then reported and the exit code is non-zero.
"""
import argparse, hashlib, json, os, shutil, sys, tempfile
from pathlib import Path

JOURNAL = ".copysafe-journal.json"

def sha256(p):
    h = hashlib.sha256()
    with open(p, "rb") as f:
        while True:
            b = f.read(1 << 20)
            if not b:
                break
            h.update(b)
    return h.hexdigest()

def selftest():
    with tempfile.TemporaryDirectory() as td:
        base = Path(td)
        src = base / "src"; dst = base / "dst"
        (src / "sub").mkdir(parents=True)
        (src / "a.txt").write_text("alpha")
        (src / "sub" / "b.bin").write_bytes(bytes(range(256)) * 40)
        import subprocess
        r = subprocess.run([sys.executable, __file__, str(src), str(dst)],
                           capture_output=True, text=True)
        assert r.returncode == 0, r.stderr
        assert (dst / "a.txt").read_text() == "alpha"
        assert sha256(dst / "sub" / "b.bin") == sha256(src / "sub" / "b.bin")
        # resume run: everything already verified, nothing recopied
        r = subprocess.run([sys.executable, __file__, str(src), str(dst), "--resume"],
                           capture_output=True, text=True)
        assert r.returncode == 0, r.stderr
        assert "skipped" in r.stdout.lower() or "already" in r.stdout.lower(), r.stdout
        print("selftest OK: copy verified by hash, resume run skipped verified files")
        return 0

def main():
    ap = argparse.ArgumentParser(description="copysafe - copy a tree with hash verification and resume")
    ap.add_argument("src", nargs="?")
    ap.add_argument("dest", nargs="?")
    ap.add_argument("--resume", action="store_true")
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    if not a.src or not a.dest:
        ap.error("src and dest are required")
    src, dst = Path(a.src), Path(a.dest)
    if not src.is_dir():
        print(f"copysafe: {a.src}: not a directory", file=sys.stderr); return 2
    dst.mkdir(parents=True, exist_ok=True)
    journal_path = dst / JOURNAL
    journal = {}
    if a.resume and journal_path.exists():
        try:
            journal = json.load(open(journal_path))
        except (json.JSONDecodeError, OSError):
            journal = {}
    files = sorted(p for p in src.rglob("*") if p.is_file())
    copied, skipped, failed = 0, 0, []
    for p in files:
        rel = str(p.relative_to(src))
        target = dst / rel
        target.parent.mkdir(parents=True, exist_ok=True)
        entry = journal.get(rel)
        if a.resume and entry:
            if target.exists():
                st = target.stat()
                if st.st_size == entry["size"] and int(st.st_mtime) == entry["mtime"]:
                    skipped += 1
                    continue
        ok = False
        for attempt in range(2):
            shutil.copy2(str(p), str(target))
            if sha256(target) == sha256(p):
                ok = True
                break
        if ok:
            st = target.stat()
            journal[rel] = {"size": st.st_size, "mtime": int(st.st_mtime),
                            "sha256": sha256(target)}
            copied += 1
        else:
            failed.append(rel)
        # flush journal as we go so an interruption keeps progress
        with open(journal_path, "w") as f:
            json.dump(journal, f)
    print(f"copied {copied}, skipped {skipped} (already verified), failed {len(failed)}")
    for rel in failed:
        print(f"FAILED {rel}", file=sys.stderr)
    return 1 if failed else 0

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