#!/usr/bin/env python3
# execfix — find scripts without the executable bit, or executables with no shebang; optionally fix them.
# Usage: execfix [--fix] [--ext .sh,.py] dir
"""execfix: catch the two classic script mistakes — a script with a shebang
that isn't executable (`Permission denied` when you run it) and an executable
file with no shebang (runs as shell garbage). Lists both kinds, and --fix
sets/clears the bit accordingly."""
import argparse, os, stat, sys

SCRIPT_EXTS = {".sh", ".py", ".pl", ".rb", ".js", ".bash", ".zsh"}

def scan(root, fix=False, exts=None):
    exts = exts or SCRIPT_EXTS
    no_exec, no_shebang = [], []
    for dirpath, _, filenames in os.walk(root):
        for name in filenames:
            p = os.path.join(dirpath, name)
            try: st = os.lstat(p)
            except OSError: continue
            if os.path.islink(p) or not stat.S_ISREG(st.st_mode): continue
            try:
                with open(p, "rb") as f: head = f.read(2)
            except OSError: continue
            has_shebang = head == b"#!"
            is_exec = bool(st.st_mode & 0o111)
            looks_script = has_shebang or os.path.splitext(name)[1].lower() in exts
            if has_shebang and not is_exec: no_exec.append(p)
            elif is_exec and not has_shebang and looks_script: no_shebang.append(p)
    print(f"execfix: {len(no_exec)} scripts missing the exec bit, {len(no_shebang)} executables missing a shebang")
    for p in no_exec: print(f"  NOEXEC   {p}")
    for p in no_shebang: print(f"  NOSHEBANG {p}")
    if fix:
        for p in no_exec:
            os.chmod(p, os.stat(p).st_mode | 0o755); print(f"  fixed +x {p}")
        for p in no_shebang:
            os.chmod(p, os.stat(p).st_mode & ~0o111); print(f"  fixed -x {p}")
    elif no_exec or no_shebang:
        print("dry run — pass --fix to correct the bits")
    return 0

def selftest():
    import tempfile
    with tempfile.TemporaryDirectory() as d:
        a = os.path.join(d, "a.sh"); open(a, "w").write("#!/bin/sh\necho hi\n"); os.chmod(a, 0o644)
        b = os.path.join(d, "b.sh"); open(b, "w").write("echo hi\n"); os.chmod(b, 0o755)
        c = os.path.join(d, "c.sh"); open(c, "w").write("#!/bin/sh\necho hi\n"); os.chmod(c, 0o755)
        assert scan(d, fix=True) == 0
        assert os.stat(a).st_mode & 0o111
        assert not (os.stat(b).st_mode & 0o111)
    print("execfix selftest: PASS"); return 0

def main():
    ap = argparse.ArgumentParser(description="Find scripts without the exec bit, or executables with no shebang; optionally fix them.")
    ap.add_argument("dir", nargs="?", default=".")
    ap.add_argument("--fix", action="store_true")
    ap.add_argument("--ext", default=None, help="extra script extensions, comma-separated (e.g. .sh,.py)")
    ap.add_argument("--selftest", action="store_true")
    a = ap.parse_args()
    if a.selftest: return selftest()
    exts = set(e if e.startswith(".") else "." + e for e in a.ext.split(",")) if a.ext else None
    return scan(a.dir, a.fix, exts)

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