#!/usr/bin/env python3
# scriptcheck - syntax-check all shell scripts in a directory (bash -n) and report
# Usage: scriptcheck [DIR] [--ext .sh] [--all] [--recursive]
import argparse, os, subprocess, sys

SHEBANGS = ("#!/bin/bash", "#!/bin/sh", "#!/usr/bin/env bash", "#!/usr/bin/env sh")

def is_script(path):
    if path.endswith(".sh") or path.endswith(".bash"):
        return True
    try:
        with open(path, "rb") as f:
            head = f.read(64).decode(errors="replace")
        return head.startswith(SHEBANGS)
    except OSError:
        return False

def check(path):
    r = subprocess.run(["bash", "-n", path], capture_output=True, text=True)
    return r.returncode == 0, r.stderr.strip()

def selftest():
    import tempfile
    with tempfile.TemporaryDirectory() as d:
        open(os.path.join(d, "good.sh"), "w").write("#!/bin/bash\necho hi\nif true; then echo ok; fi\n")
        open(os.path.join(d, "bad.sh"), "w").write("#!/bin/bash\nif true; then echo oops\n")
        out = subprocess.run([sys.executable, os.path.abspath(__file__), d],
                             capture_output=True, text=True)
        assert out.returncode == 1, out.stdout  # failures -> exit 1
        assert "good.sh" in out.stdout and "PASS" in out.stdout
        assert "bad.sh" in out.stdout and "FAIL" in out.stdout
        print("scriptcheck selftest: PASS")
    return 0

def main():
    ap = argparse.ArgumentParser(prog="scriptcheck",
        description="Syntax-check all shell scripts in a directory (bash -n) and report.")
    ap.add_argument("dir", nargs="?", default=".", help="directory to scan (default: .)")
    ap.add_argument("--recursive", "-r", action="store_true", help="recurse into subdirectories")
    ap.add_argument("--selftest", action="store_true", help="run built-in self-test and exit")
    a = ap.parse_args()
    if a.selftest:
        return selftest()
    files = []
    if a.recursive:
        for root, dirs, names in os.walk(a.dir):
            dirs[:] = [d for d in dirs if d not in (".git", "__pycache__")]
            for n in names:
                files.append(os.path.join(root, n))
    else:
        for n in sorted(os.listdir(a.dir)):
            p = os.path.join(a.dir, n)
            if os.path.isfile(p):
                files.append(p)
    scripts = [p for p in files if is_script(p)]
    if not scripts:
        print("scriptcheck: no shell scripts found in %s" % a.dir); return 0
    ok = bad = 0
    for p in sorted(scripts):
        good, err = check(p)
        if good:
            print("PASS  %s" % p); ok += 1
        else:
            print("FAIL  %s" % p); bad += 1
            for line in err.splitlines()[:3]:
                print("      %s" % line)
    print("scriptcheck: %d passed, %d failed, %d scripts." % (ok, bad, len(scripts)))
    return 1 if bad else 0

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