"""Test the `tinydns-conf` tool and the generated directory."""

from __future__ import annotations

import os
import pwd
import sys
import typing

from . import defs


if typing.TYPE_CHECKING:
    import pathlib


TINYDNS = "/usr/sbin/tinydns"


def test_tinydns_conf(cfg: defs.Config, tempd: pathlib.Path) -> None:
    """Test the operation of `tinydns-conf`."""
    print("\n==== test_tinydns_conf")
    ipaddr = defs.RECORDS[0].address
    svcacct = pwd.getpwuid(os.getuid()).pw_name
    svcdir = tempd / defs.SVCDIR
    if svcdir.exists():
        sys.exit(f"Did not expect {svcdir} to exist")

    tconf = cfg.sbindir / "tinydns-conf"
    if not tconf.is_file() or not os.access(tconf, os.X_OK):
        sys.exit(f"Not an executable file: {tconf}")

    cmd: list[pathlib.Path | str] = [
        tconf,
        svcacct,
        svcacct,
        svcdir,
        ipaddr,
    ]
    outp = cfg.check_output(cmd)
    if outp:
        sys.exit(f"{cmd!r} produced output: {outp!r}")

    cfg.check_call(["find", "--", svcdir, "-ls"])

    if not svcdir.is_dir():
        sys.exit(f"{cmd!r} did not create {svcdir}")

    ipfile = svcdir / "env/IP"
    if not ipfile.is_file():
        sys.exit(f"{cmd!r} did not create {ipfile}")
    iptext = ipfile.read_text(encoding=defs.MINENC)
    cfg.diag(f"{ipfile}: {iptext!r}")
    if iptext != ipaddr + "\n":
        sys.exit(f"{cmd!r} created {ipfile} with weird contents: {iptext!r}")

    runfile = svcdir / "run"
    if not runfile.is_file():
        sys.exit(f"{cmd!r} did not create {runfile}")
    lines = runfile.read_text(encoding=defs.MINENC).splitlines()
    cfg.diag(f"{runfile} last line: {lines[-1]!r}")
    if lines[0] != "#!/bin/sh" or not lines[-1].endswith(" " + TINYDNS):
        sys.exit(f"{cmd!r} created unexpected {runfile}: {lines!r}")

    lines[-1] = lines[-1].replace(" " + TINYDNS, " " + str(cfg.sbindir / "tinydns"))
    runfile.write_text("".join(line + "\n" for line in lines), encoding=defs.MINENC)
    cfg.check_call(["cat", "--", runfile])

    data_cdb = svcdir / "root/data.cdb"
    data_cdb.write_bytes((tempd / "data.cdb").read_bytes())
    cfg.check_call(["stat", "--", data_cdb])
