#!/usr/bin/env python3
# metacopy — copy timestamps and permissions (and xattrs, best effort) from one file to another.
# Usage: metacopy [--times-only] [--perms-only] [--xattrs] source dest
"""metacopy: clone a file's metadata without touching its content. Useful
when a tool rewrites a file and loses its mtime/mode — point metacopy at the
original and the copy inherits timestamps, permissions and (with --xattrs)
extended attributes. Reports exactly what changed."""
import argparse, os, shutil, sys

def copy_meta(src, dest, times=True, perms=True, xattrs=False):
    if not os.path.exists(src): print(f"metacopy: {src}: no such file", file=sys.stderr); return 1
    if not os.path.exists(dest): print(f"metacopy: {dest}: no such file", file=sys.stderr); return 1
    st = os.stat(src)
    changes = []
    if perms:
        os.chmod(dest, stat_mode(st.st_mode)); changes.append(f"mode -> {oct(stat_mode(st.st_mode))}")
    if times:
        os.utime(dest, ns=(st.st_atime_ns, st.st_mtime_ns)); changes.append(f"mtime -> {st.st_mtime}")
    if xattrs:
        try:
            for name in os.listxattr(src):
                try:
                    os.setxattr(dest, name, os.getxattr(src, name)); changes.append(f"xattr {name}")
                except OSError as e: print(f"metacopy: xattr {name}: {e}", file=sys.stderr)
        except OSError as e:
            print(f"metacopy: xattrs unavailable: {e}", file=sys.stderr)
    try:
        os.chown(dest, st.st_uid, st.st_gid); changes.append(f"owner -> {st.st_uid}:{st.st_gid}")
    except PermissionError:
        print("metacopy: owner not copied (need root / same uid)", file=sys.stderr)
    except OSError as e:
        print(f"metacopy: chown: {e}", file=sys.stderr)
    print(f"metacopy: {src} -> {dest}: " + ("; ".join(changes) if changes else "nothing copied"))
    return 0

def stat_mode(m):
    import stat as _s; return _s.S_IMODE(m)

def selftest():
    import tempfile, time
    with tempfile.TemporaryDirectory() as d:
        s = os.path.join(d, "s"); t = os.path.join(d, "t")
        open(s, "w").write("src"); open(t, "w").write("dst")
        os.chmod(s, 0o640); os.utime(s, ns=(1_000_000_000_000_000_000, 1_200_000_000_000_000_000))
        assert copy_meta(s, t) == 0
        st = os.stat(t)
        assert stat_mode(st.st_mode) == 0o640 and st.st_mtime_ns == 1_200_000_000_000_000_000
    print("metacopy selftest: PASS"); return 0

def main():
    ap = argparse.ArgumentParser(description="Copy timestamps, permissions (and optionally xattrs/owner) from one file to another.")
    ap.add_argument("source", nargs="?"); ap.add_argument("dest", nargs="?")
    ap.add_argument("--times-only", action="store_true")
    ap.add_argument("--perms-only", action="store_true")
    ap.add_argument("--xattrs", action="store_true", help="also copy extended attributes")
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest: return selftest()
    if not a.source or not a.dest: ap.error("need source and dest")
    times = not a.perms_only; perms = not a.times_only
    return copy_meta(a.source, a.dest, times, perms, a.xattrs)

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