#!/usr/bin/env python3
"""Run a .protel file invoked via shebang (Introductory Manual §7.0.5).

The kernel executes: protel-run /path/to/script.protel [program args]
"""

from __future__ import annotations

import os
import sys
from pathlib import Path

_ROOT = Path(__file__).resolve().parent
_PROTEL = _ROOT / "protel"


def main() -> int:
    if len(sys.argv) < 2:
        print(
            "protel-run: missing PROTEL source path "
            "(use #!/usr/bin/env protel-run in a .protel file)",
            file=sys.stderr,
        )
        return 2

    source = Path(sys.argv[1]).resolve()
    program_args = sys.argv[2:]

    if not _PROTEL.is_file():
        print(f"protel-run: cannot find protel driver at '{_PROTEL}'", file=sys.stderr)
        return 1

    argv = [str(_PROTEL), str(source), "--run", "--", *program_args]
    os.execv(str(_PROTEL), argv)
    return 1


if __name__ == "__main__":
    raise SystemExit(main())