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)

    sys.path.append("hybrid_server")
    sys.path.append(".")
    os.chdir("hybrid_server")

    #import stacktracer
    #stacktracer.trace_start("trace.html",interval=5,auto=True) # Set auto flag to always update file!

    import server
    import sccd.runtime.socket2event as socket2event

    controller = server.Controller([port])
    socket2event.boot_translation_service(controller)
    controller.start()

except KeyboardInterrupt:
    pass

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