#!/usr/bin/env python3
# archconv — convert an archive between zip and tar.gz, verifying content hashes match after conversion.
# Usage: archconv [--to zip|tar.gz] [--keep] archive
"""archconv: convert zip <-> tar.gz with proof. It extracts members to a temp
dir, rebuilds in the target format, then compares per-file SHA-256 hashes
before/after and reports the conversion verified — format migration you can
trust, not a blind repack."""
import argparse, hashlib, os, shutil, sys, tarfile, tempfile, zipfile

def hashes_of_members(path):
    h = {}
    if path.endswith(".zip"):
        with zipfile.ZipFile(path) as z:
            for i in z.infolist():
                if not i.is_dir(): h[i.filename] = hashlib.sha256(z.read(i.filename)).hexdigest()
    else:
        with tarfile.open(path, "r:*") as t:
            for m in t.getmembers():
                if m.isfile():
                    f = t.extractfile(m); h[m.name] = hashlib.sha256(f.read()).hexdigest()
    return h

def convert(path, to, keep=False):
    if not os.path.isfile(path):
        print(f"archconv: {path}: no such file", file=sys.stderr); return 1
    src_is_zip = path.lower().endswith(".zip")
    if to == "zip":
        dest = os.path.splitext(path)[0] + ".zip" if not src_is_zip else path + ".converted.zip"
    else:
        dest = (os.path.splitext(path)[0] + ".tar.gz") if src_is_zip else path + ".converted.tar.gz"
    if os.path.abspath(dest) == os.path.abspath(path):
        dest = path + ".converted." + ("zip" if to == "zip" else "tar.gz")
    before = hashes_of_members(path)
    with tempfile.TemporaryDirectory() as d:
        if src_is_zip:
            with zipfile.ZipFile(path) as z: z.extractall(d)
        else:
            with tarfile.open(path, "r:*") as t: t.extractall(d, filter="data")
        if to == "zip":
            with zipfile.ZipFile(dest, "w", zipfile.ZIP_DEFLATED) as z:
                for root, _, files in os.walk(d):
                    for f in sorted(files):
                        fp = os.path.join(root, f)
                        z.write(fp, os.path.relpath(fp, d))
        else:
            with tarfile.open(dest, "w:gz") as t:
                for root, _, files in os.walk(d):
                    for f in sorted(files):
                        fp = os.path.join(root, f)
                        t.add(fp, arcname=os.path.relpath(fp, d))
    after = hashes_of_members(dest)
    if before == after:
        print(f"archconv: {path} -> {dest}: VERIFIED ({len(before)} files, hashes match)")
    else:
        print(f"archconv: {path} -> {dest}: MISMATCH! before={len(before)} after={len(after)}", file=sys.stderr)
        return 1
    if not keep:
        os.remove(path); print(f"removed source {path} (use --keep to retain)")
    return 0

def selftest():
    import tempfile, zipfile
    with tempfile.TemporaryDirectory() as d:
        src = os.path.join(d, "a.zip")
        with zipfile.ZipFile(src, "w", zipfile.ZIP_DEFLATED) as z:
            z.writestr("x.txt", "hello" * 100); z.writestr("sub/y.txt", "world" * 50)
        assert convert(src, "tar.gz", keep=True) == 0
        assert convert(os.path.join(d, "a.tar.gz"), "zip", keep=True) == 0
    print("archconv selftest: PASS"); return 0

def main():
    ap = argparse.ArgumentParser(description="Convert an archive between zip and tar.gz, verifying hashes match.")
    ap.add_argument("archive", nargs="?", help="archive to convert")
    ap.add_argument("--to", choices=["zip", "tar.gz"], help="target format (default: the other one)")
    ap.add_argument("--keep", action="store_true", help="keep the source archive")
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest: return selftest()
    if not a.archive: ap.error("need an archive")
    to = a.to or ("tar.gz" if a.archive.lower().endswith(".zip") else "zip")
    return convert(a.archive, to, a.keep)

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