import subprocess
import sys
import os

# sys.executable to use the same Python interpreter used to invoke this command
if len(sys.argv) < 2:
    port = "8001"
else:
    port = sys.argv[1]

try:
    # Compile all SCCD models first
    os.chdir("wrappers")
    subprocess.check_call([sys.executable, "-m", "sccd.compiler.sccdc", "-p", "threads", "modelverse_SCCD.xml"])

    os.chdir("../hybrid_server")
    subprocess.check_call([sys.executable, "-m", "sccd.compiler.sccdc", "-p", "threads", "server.xml"])

    os.chdir("..")

    # Start up all services with auto-detection
    import glob
    service_paths = glob.glob("services/*/main.py")
    services = []
    for service_path in service_paths:
        print("[SERVICE] loaded " + service_path)
        service = subprocess.Popen([sys.executable, service_path, "127.0.0.1:%s" % port])
        services.append(service)

    os.chdir("hybrid_server")
    #program_to_execute = [sys.executable, "run_mvk_server.py", port]
    program_to_execute = [sys.executable, "run_mvk_server.py", port, "--kernel=generated"]
    server = subprocess.Popen(program_to_execute)

    server.wait()

finally:
    # Stop the server
    try:
        server.terminate()
    except:
        pass

    # Terminate all services as well
    for service in services:
        try:
            service.terminate()
        except:
            pass
