#!/usr/bin/env python3
# txt2bin — decode a bin2txt file back to binary, verifying the sha256 in its header.
# Usage: txt2bin [--output NAME] input.txt [output.bin]
"""txt2bin: the other half of bin2txt. It reads the `# bin2txt v1` header,
decodes the body (base64 or hex per the header), restores the original
filename when no output is given, and verifies the SHA-256 — refusing to
write a file whose hash doesn't match the header."""
import argparse, base64, hashlib, os, sys

def decode(inp, out=None):
    lines = open(inp, "r", errors="replace").read().splitlines()
    if not lines or lines[0].strip() != "# bin2txt v1":
        print("txt2bin: not a bin2txt file (missing '# bin2txt v1' header)", file=sys.stderr); return 1
    meta = {}
    body = []
    in_body = False
    for line in lines[1:]:
        if not in_body and line.startswith("# "):
            if ":" in line:
                k, v = line[2:].split(":", 1); meta[k.strip()] = v.strip()
            continue
        if not in_body and line == "#":
            in_body = True; continue
        body.append(line)
    algo = meta.get("algo", "base64")
    payload = "".join(body)
    try:
        data = bytes.fromhex(payload) if algo == "hex" else base64.b64decode("".join(payload.split()), validate=True)
    except Exception as e:
        print(f"txt2bin: decode failed: {e}", file=sys.stderr); return 1
    if "size" in meta and len(data) != int(meta["size"]):
        print(f"txt2bin: size mismatch: header says {meta['size']}, decoded {len(data)}", file=sys.stderr); return 1
    if "sha256" in meta:
        actual = hashlib.sha256(data).hexdigest()
        if actual != meta["sha256"]:
            print(f"txt2bin: SHA-256 MISMATCH: header {meta['sha256'][:16]}..., got {actual[:16]}...", file=sys.stderr); return 1
    if out is None:
        out = meta.get("filename") or (os.path.splitext(os.path.basename(inp))[0] + ".bin")
    open(out, "wb").write(data)
    print(f"txt2bin: wrote {out} ({len(data)} bytes, sha256 verified)")
    return 0

def selftest():
    import tempfile, subprocess
    with tempfile.TemporaryDirectory() as d:
        src = os.path.join(d, "orig.bin"); open(src, "wb").write(bytes(range(256)) * 4)
        txt = os.path.join(d, "orig.txt")
        r = subprocess.run(["/root/fileutils/bin/bin2txt", src, txt], capture_output=True)
        assert r.returncode == 0, r.stderr
        back = os.path.join(d, "back.bin")
        assert decode(txt, back) == 0
        assert open(back, "rb").read() == open(src, "rb").read()
        # tampered body must fail verification
        bad = os.path.join(d, "bad.txt")
        lines = open(txt).read().splitlines()
        lines[-1] = ("A" if lines[-1][0] != "A" else "B") + lines[-1][1:]
        open(bad, "w").write("\n".join(lines) + "\n")
        assert decode(bad, os.path.join(d, "bad.bin")) == 1
        # non-bin2txt input rejected
        plain = os.path.join(d, "plain.txt"); open(plain, "w").write("hello\n")
        assert decode(plain, os.path.join(d, "x.bin")) == 1
    print("txt2bin selftest: PASS (round-trip verified, tamper rejected)"); return 0

def main():
    ap = argparse.ArgumentParser(description="Decode a bin2txt file back to binary, verifying its header SHA-256.")
    ap.add_argument("input", nargs="?"); ap.add_argument("output", nargs="?")
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest: return selftest()
    if not a.input: ap.error("need an input .txt file")
    return decode(a.input, a.output)

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