#!/usr/bin/python3
"""Exercise the installed portop without opening any port: version,
configuration, JSON output and the baseline comparison."""

import json
import os
from pathlib import Path
import subprocess
import tempfile


def run(*args, env=None, check=True):
    result = subprocess.run(["portop", *args], text=True, capture_output=True, timeout=60, env=env)
    if check and result.returncode != 0:
        raise SystemExit(f"portop {' '.join(args)} exited {result.returncode}: {result.stderr}")
    return result


flags = ["--no-dns", "--no-systemd", "--no-docker", "--no-firewall"]

assert run("--version").stdout.startswith("portop ")

rows = json.loads(run("--json", *flags).stdout)
assert isinstance(rows, list)
for row in rows:
    assert row["protocol"] in ("TCP", "UDP") and "local_port" in row and "state" in row, row

with tempfile.TemporaryDirectory() as temp:
    env = dict(os.environ, XDG_CONFIG_HOME=temp)
    run("--init-config", env=env)
    assert (Path(temp) / "portop" / "config.yml").is_file()

    # A baseline saved now matches the sockets a moment later, unless
    # something else on the machine opened or closed a port meanwhile;
    # --diff exits 0 for no change and 3 for a change, never anything else.
    baseline = str(Path(temp) / "baseline.json")
    run("--save-baseline", "--baseline-path", baseline, *flags)
    assert Path(baseline).is_file()
    diff = run("--diff", "--baseline-path", baseline, "--json", *flags, check=False)
    assert diff.returncode in (0, 3), (diff.returncode, diff.stderr)
    report = json.loads(diff.stdout)
    assert "added" in report and "removed" in report, report

print("Installed portop: version, JSON output, configuration and baseline passed")
