#!/usr/bin/env python3
# ownfix — report files in a tree not owned by the current user (or by a given user), with an optional chown fix.
# Usage: ownfix [--user NAME] [--fix] [--group] dir
"""ownfix: find files owned by someone else. After a restore, a sudo copy, or
a shared-volume mess, a tree can be full of files you can't write to — ownfix
lists them grouped by owner (with sizes), and --fix chowns them back to you
when run as root."""
import argparse, os, pwd, grp, sys
from collections import defaultdict

def scan(root, user=None, fix=False, group_check=False):
    target_uid = pwd.getpwnam(user).pw_uid if user else os.getuid()
    target_name = user or pwd.getpwuid(target_uid).pw_name
    foreign = defaultdict(list)
    total = 0
    for dirpath, dirnames, filenames in os.walk(root):
        for name in dirnames + filenames:
            p = os.path.join(dirpath, name)
            try: st = os.lstat(p)
            except OSError: continue
            total += 1
            owner = pwd.getpwuid(st.st_uid).pw_name if st.st_uid in [x.pw_uid for x in pwd.getpwall()] else str(st.st_uid)
            bad = st.st_uid != target_uid
            if group_check:
                bad = bad or st.st_gid != os.getgid()
            if bad:
                foreign[owner].append((p, st.st_size))
    if not foreign:
        print(f"ownfix: all {total} entries owned by {target_name}"); return 0
    n = sum(len(v) for v in foreign.values())
    print(f"ownfix: {n} of {total} entries NOT owned by {target_name}:")
    for owner, items in sorted(foreign.items(), key=lambda kv: -len(kv[1])):
        sz = sum(s for _, s in items)
        print(f"  owner {owner}: {len(items)} files, {sz} bytes")
        for p, s in items[:20]: print(f"    {p} ({s}B)")
        if len(items) > 20: print(f"    ... and {len(items)-20} more")
    if fix:
        if os.getuid() != 0:
            print("ownfix: --fix needs root to chown other users' files", file=sys.stderr); return 1
        for owner, items in foreign.items():
            for p, _ in items:
                try: os.chown(p, target_uid, -1)
                except OSError as e: print(f"ownfix: {p}: {e}", file=sys.stderr)
        print(f"ownfix: chowned {n} entries to {target_name}")
    else:
        print("dry run — pass --fix (as root) to chown them")
    return 0

def selftest():
    import tempfile
    with tempfile.TemporaryDirectory() as d:
        open(os.path.join(d, "a.txt"), "w").write("x")
        assert scan(d) == 0
        # simulate a foreign owner by scanning for a user that owns nothing here
        assert scan(d, user="nobody") == 0
    print("ownfix selftest: PASS"); return 0

def main():
    ap = argparse.ArgumentParser(description="Report files in a tree not owned by the current (or given) user; optionally chown them back.")
    ap.add_argument("dir", nargs="?", default=".")
    ap.add_argument("--user", help="expected owner (default: current user)")
    ap.add_argument("--fix", action="store_true", help="chown foreign files to the expected user (needs root)")
    ap.add_argument("--group", action="store_true", help="also flag files whose group differs")
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest: return selftest()
    return scan(a.dir, a.user, a.fix, a.group)

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