#!/usr/bin/env python3
# permfix — normalize permissions (files 644, dirs 755, scripts 755) with a preview and an undo list.
# Usage: permfix [--apply] [--undo-file FILE] [--dry-run] dir
"""permfix: fix a tree's permissions in one pass, safely. It previews every
change first (files 644, directories 755, files with a shebang 755), writes an
undo script that restores the old modes, and only applies when you pass
--apply — no silent chmod -R."""
import argparse, os, stat, sys

def plan(root):
    changes = []  # (path, old_mode, new_mode)
    for dirpath, dirnames, filenames in os.walk(root):
        for name in dirnames:
            p = os.path.join(dirpath, name)
            try: m = stat.S_IMODE(os.lstat(p).st_mode)
            except OSError: continue
            if m != 0o755: changes.append((p, m, 0o755))
        for name in filenames:
            p = os.path.join(dirpath, name)
            try:
                st = os.lstat(p); m = stat.S_IMODE(st.st_mode)
            except OSError: continue
            if os.path.islink(p): continue
            new = 0o644
            try:
                with open(p, "rb") as f:
                    if f.read(2) == b"#!": new = 0o755
            except OSError: pass
            if m != new: changes.append((p, m, new))
    return changes

def run(root, apply=False, undo_file=None):
    changes = plan(root)
    if not changes:
        print("permfix: permissions already normal"); return 0
    for p, old, new in changes:
        print(f"  {oct(old)} -> {oct(new)}  {p}")
    print(f"permfix: {len(changes)} changes planned")
    if undo_file:
        with open(undo_file, "w") as f:
            f.write("#!/bin/sh\n# permfix undo — restores previous modes\n")
            for p, old, new in changes:
                f.write(f"chmod {oct(old)[2:]} {p!r}\n".replace("'", "'\\''"))
        os.chmod(undo_file, 0o755)
        print(f"undo script written to {undo_file}")
    if not apply:
        print("dry run — pass --apply to make these changes")
        return 0
    for p, old, new in changes:
        os.chmod(p, new)
    print(f"permfix: applied {len(changes)} changes")
    return 0

def selftest():
    import tempfile
    with tempfile.TemporaryDirectory() as d:
        f = os.path.join(d, "a.txt"); open(f, "w").write("x"); os.chmod(f, 0o777)
        s = os.path.join(d, "run.sh"); open(s, "w").write("#!/bin/sh\necho hi\n"); os.chmod(s, 0o600)
        sub = os.path.join(d, "sub"); os.mkdir(sub); os.chmod(sub, 0o700)
        ch = plan(d)
        assert len(ch) == 3, ch
        assert run(d, apply=True, undo_file=os.path.join(d, "undo.sh")) == 0
        assert stat.S_IMODE(os.stat(f).st_mode) == 0o644
        assert stat.S_IMODE(os.stat(s).st_mode) == 0o755
        assert stat.S_IMODE(os.stat(sub).st_mode) == 0o755
    print("permfix selftest: PASS"); return 0

def main():
    ap = argparse.ArgumentParser(description="Normalize tree permissions (files 644, dirs 755, scripts 755) with preview + undo script.")
    ap.add_argument("dir", nargs="?", default=".")
    ap.add_argument("--apply", action="store_true", help="actually change permissions (default is preview)")
    ap.add_argument("--undo-file", default=None, help="write an undo shell script here")
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest: return selftest()
    return run(a.dir, a.apply, a.undo_file)

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