import os
import socket
import yatest.common
from yatest.common.network import PortManager
from library.python.testing.recipe import declare_recipe, set_env


def start(argv):
    pm = PortManager()
    port = str(pm.get_port())
    with open("recipe.port", "w") as f:
        f.write(str(port))
    set_env("RECIPE_PORT", port)

    global RESPONSE_STRING
    RESPONSE_STRING = " ".join(argv)

    pid = os.fork()
    if pid == 0:
        proc = yatest.common.execute(
            [
                yatest.common.binary_path("load/projects/tank_finder/tank_finder"),
                "-p", port 
            ],
            check_exit_code=True 
        )
    else:
        with open("recipe.pid", "w") as f:
            f.write(str(pid))


def stop(argv):
    with open("recipe.pid") as f:
        pid = int(f.read())
        os.kill(pid, 9)

if __name__ == "__main__":
    declare_recipe(start, stop)
