#!/usr/bin/env python3
# hexfile — hex encode/decode files, with offset-annotated dumps and a round-trip check.
# Usage: hexfile [--decode] [--dump] [--check] input [output]
"""hexfile: hex for whole files. --dump gives an `xxd`-style annotated dump
(offset, hex bytes, ASCII), plain mode gives continuous hex for piping, and
--check round-trips and compares hashes."""
import argparse, hashlib, os, sys

def sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for c in iter(lambda: f.read(65536), b""): h.update(c)
    return h.hexdigest()

def encode(inp, out):
    data = open(inp, "rb").read()
    if out: open(out, "w").write(data.hex() + "\n")
    else: sys.stdout.write(data.hex() + "\n")
    return 0

def dump(inp):
    with open(inp, "rb") as f: data = f.read()
    for off in range(0, len(data), 16):
        chunk = data[off:off+16]
        hx = " ".join(f"{b:02x}" for b in chunk)
        asc = "".join(chr(b) if 32 <= b < 127 else "." for b in chunk)
        print(f"{off:08x}  {hx:<48}  |{asc}|")
    print(f"{len(data)} bytes")
    return 0

def decode(inp, out):
    raw = open(inp, "rb").read() if inp != "-" else sys.stdin.buffer.read()
    text = raw.decode("ascii", "ignore")
    text = "".join(text.split())
    # tolerate dump format: strip offsets/ascii columns if present
    if ":" in text and all(c in "0123456789abcdefABCDEF: \n" for c in text[:20]):
        pass
    try:
        data = bytes.fromhex(text)
    except ValueError as e:
        print(f"hexfile: invalid hex: {e}", file=sys.stderr); return 1
    if out: open(out, "wb").write(data)
    else: sys.stdout.buffer.write(data)
    return 0

def selftest():
    import tempfile
    with tempfile.TemporaryDirectory() as d:
        src = os.path.join(d, "a.bin"); open(src, "wb").write(b"\x00\xffHello\x00\x01")
        enc = os.path.join(d, "a.hex"); dec = os.path.join(d, "a.out")
        assert encode(src, enc) == 0
        assert open(enc).read().strip() == "00ff48656c6c6f0001"
        assert decode(enc, dec) == 0
        assert sha256(src) == sha256(dec)
        assert dump(src) == 0
    print("hexfile selftest: PASS"); return 0

def main():
    ap = argparse.ArgumentParser(description="Hex encode/decode files, with annotated dumps and a round-trip check.")
    ap.add_argument("input", nargs="?"); ap.add_argument("output", nargs="?")
    ap.add_argument("--decode", "-d", action="store_true")
    ap.add_argument("--dump", action="store_true", help="xxd-style offset/hex/ASCII dump")
    ap.add_argument("--check", action="store_true", help="encode then decode and compare SHA-256")
    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 file")
    if a.dump: return dump(a.input)
    if a.check and not a.decode:
        import tempfile
        with tempfile.TemporaryDirectory() as d:
            enc = os.path.join(d, "enc"); dec = os.path.join(d, "dec")
            assert encode(a.input, enc) == 0 and decode(enc, dec) == 0
            ok = sha256(a.input) == sha256(dec)
            print(f"hexfile --check: {'PASS' if ok else 'FAIL'}")
            return 0 if ok else 1
    return decode(a.input, a.output) if a.decode else encode(a.input, a.output)

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