#!/usr/bin/python3
"""Run the feature-check test suite with several Python interpreters."""

import os
import pathlib
import re
import subprocess
import sys

from typing import List


def find_interpreters() -> List[pathlib.Path]:
    """Determine the list of supported Python interpreters."""
    paths = [
        pathlib.Path("/usr/bin/" + line)
        for line in re.split(
            r"[ \t\r\n]",
            subprocess.check_output(
                ["py3versions", "-s"], shell=False, encoding="UTF-8"
            ),
        )
        if line
    ]
    missing = [path for path in paths if not path.is_file()]
    if missing:
        sys.exit(
            "Missing/invalid Python interpreters: {missing}".format(
                missing=" ".join(map(str, missing))
            )
        )

    return paths


def main() -> None:
    """The main program: fetch the list of interpreters, run things."""
    if hasattr(sys.stdout, "reconfigure"):
        sys.stdout.reconfigure(line_buffering=True)  # type: ignore

    interpreters = find_interpreters()

    test_script = pathlib.Path("test-python/python/python-fcheck.sh")
    test_script.parent.mkdir(mode=0o755, parents=True, exist_ok=True)

    test_env = dict(os.environ)
    test_env["TEST_PROG"] = str(test_script)

    for interp in interpreters:
        print("\n\n============ Testing {interp}\n".format(interp=interp))
        test_script.write_text(
            "'{interp}' -m feature_check \"$@\"".format(interp=interp),
            encoding="UTF-8",
        )
        print(test_script.read_text(encoding="UTF-8"))
        test_script.chmod(0o755)

        subprocess.check_call(["prove", "t"], shell=False, env=test_env)

    print("\n\n============ The TAP tests passed for all Python versions\n")


if __name__ == "__main__":
    main()
