"""Run the Ubuntu package binaries on five public PP-284 zone files.

Set PP284_WORKDIR to the extracted package directory described in method.md.
Pass --validns-all to reproduce the initial optional-policy calibration run.
"""

import json
import os
from pathlib import Path
import subprocess
import sys

HERE = Path(__file__).resolve().parent
ROOT = Path(os.environ.get("PP284_WORKDIR", "./pp284-work")).resolve()
BIN = ROOT / "usr/bin"
CASES = ["valid", "syntax", "missing-mx", "cname-conflict", "missing-glue"]
ALL = sys.argv[1:] == ["--validns-all"]
if sys.argv[1:] and not ALL:
    raise SystemExit("usage: run-smoke.py [--validns-all]")

rows = []
for tool in ["named-checkzone", "kzonecheck", "validns"]:
    for case in CASES:
        zone = HERE / f"{case}.zone"
        if tool == "named-checkzone":
            command = [str(BIN / tool), "-i", "local", "pp284.test.", str(zone)]
        elif tool == "kzonecheck":
            command = [str(BIN / tool), "-o", "pp284.test.", str(zone)]
        else:
            command = [str(BIN / tool), "-z", "pp284.test."]
            if ALL:
                command.extend(["-p", "all"])
            else:
                command.extend(["-p", "cname-other-data", "-p", "mx-alias",
                                "-p", "ns-alias"])
            command.append(str(zone))
        env = dict(os.environ)
        env["LD_LIBRARY_PATH"] = str(ROOT / "usr/lib/x86_64-linux-gnu")
        try:
            proc = subprocess.run(command, capture_output=True, text=True,
                                  env=env, timeout=5, check=False)
            row = dict(tool=tool, case=case, command=command,
                       exit=proc.returncode, stdout=proc.stdout,
                       stderr=proc.stderr)
        except subprocess.TimeoutExpired as exc:
            row = dict(tool=tool, case=case, command=command,
                       exit="harness timeout", stdout=str(exc.stdout or ""),
                       stderr=str(exc.stderr or ""))
        rows.append(row)

output = ROOT / ("smoke-policy-all.json" if ALL else "smoke-results.json")
output.write_text(json.dumps(rows, indent=2) + "\n")
print(output)
