import json
import os
import shlex
import signal
import subprocess


def install_obnam(ctx):
    runcmd_prepend_to_path = globals()["runcmd_prepend_to_path"]
    srcdir = globals()["srcdir"]

    default_target = os.path.join(srcdir, "target")
    target = os.environ.get("CARGO_TARGET_DIR", default_target)
    bindir = os.path.join(target, "debug")
    assert os.path.exists(os.path.join(bindir, "obnam"))
    assert os.path.exists(os.path.join(bindir, "obnam-server"))
    runcmd_prepend_to_path(ctx, dirname=bindir)
    ctx["bindir"] = os.path.abspath(bindir)


def stdout_contains_n_lines(ctx, n=None):
    runcmd_get_stdout = globals()["runcmd_get_stdout"]
    output = runcmd_get_stdout(ctx)
    assert_eq(len(output.splitlines()), int(n))


def stdout_is_json(ctx):
    runcmd_get_stdout = globals()["runcmd_get_stdout"]
    output = runcmd_get_stdout(ctx)
    try:
        json.loads(output)
    except json.JSONDecodeError as e:
        print("stdout it not valid JSON: error at {e.lineno}:{e.colno}: {e.msg}")
        raise


def file_named_in_file_exists(ctx, filename=None):
    files_relative = globals()["files_relative"]
    files_file_exists = globals()["files_file_exists"]

    filename = files_relative(filename)
    with open(filename) as f:
        filename = f.read()
    files_file_exists(ctx, filename)


def daemon_start(ctx, argv0=None, args=None):
    bindir = ctx["bindir"]
    argv = [os.path.join(bindir, argv0)] + shlex.split(args)
    subprocess.run(
        ["daemonize", "-c", ".", "-p", "daemon.pid"] + argv,
        check=True,
    )
    started = time.time()
    while time.time() < started + 5:
        pid = open("daemon.pid").read()
        if pid:
            pid = int(pid)
            break
    ctx["daemon.pid"] = pid


def daemon_kill(ctx, **kwargs):
    pid = ctx["daemon.pid"]
    os.kill(pid, signal.SIGKILL)
