#!/opt/tasvmruntime-py/bin/python3

# Build hook script to apply default RA configuration.

from pathlib import Path
import re
import subprocess

# Location of rhino-console.
RHINO_CONSOLE = Path.home() / "rhino" / "client" / "bin" / "rhino-console"

# Name of the RA entity.
HTTP_RA_ENTITY = "http"


def run_rhino_console(cmd: list[str]) -> str:
    """
    Runs a rhino-console command.

    :param cmd: The command to run and its arguments, as separate list elements.
    :return: Output from rhino-console.
    """
    return subprocess.check_output([RHINO_CONSOLE] + cmd, text=True, stderr=subprocess.STDOUT)


def main() -> None:
    """
    Main routine.
    """

    # Determine HTTP RA ID.
    # The output will look like:
    #
    # ResourceAdaptorID[name=HTTP,vendor=OpenCloud,version=2.5]
    #
    # where the part within the square brackets is the RA ID.
    output = run_rhino_console(["listresourceadaptors"])
    for line in output.splitlines():
        if matches := re.search(r"\[(name=HTTP[^\]]+)\]", line):
            http_ra_id = matches.group(1)
            break
    else:
        raise ValueError("Could not determine HTTP RA ID")

    # Create an RA entity based on the HTTP RA type.
    run_rhino_console(["createraentity", http_ra_id, HTTP_RA_ENTITY])

    # Configure the RA entity with some default properties.
    run_rhino_console(
        [
            "updateraentityconfigproperties",
            HTTP_RA_ENTITY,
            "ListenPort", "8000",
            "SecureListenPort", "8002",
        ]
    )

    # This script is now done.
    # The before-slee-start initconf hook script configures the IP address
    # (since that isn't known until runtime),
    # creates the HTTPS keystore, and activates the RA entity and service.


if __name__ == "__main__":
    main()
