import subprocess

from conftest import LIBEXEC, env_with_fake_commands, fake_command


SYSTEMCTL_HELPER = LIBEXEC / "left4me-systemctl"


def test_systemctl_helper_passes_shell_syntax_check_and_rejects_bad_args(tmp_path):
    subprocess.run(["sh", "-n", str(SYSTEMCTL_HELPER)], check=True)
    marker = fake_command(tmp_path, "systemctl")

    for args in [
        ["bad/action", "alpha"],
        # `start` and `stop` are no longer accepted verbs — the lifecycle now
        # uses `enable`/`disable` for reboot survival via WantedBy= symlinks.
        ["start", "alpha"],
        ["stop", "alpha"],
        ["enable", ""],
        ["enable", ".hidden"],
        ["enable", "bad..name"],
        ["enable", "bad/name"],
        ["enable", "bad\\name"],
        ["enable", "bad name"],
    ]:
        result = subprocess.run(
            ["sh", str(SYSTEMCTL_HELPER), *args],
            env=env_with_fake_commands(tmp_path),
            check=False,
        )
        assert result.returncode != 0
        assert not marker.exists()

    script = SYSTEMCTL_HELPER.read_text()
    assert 'unit="left4me-server@${name}.service"' in script
    assert 'enable) exec "$systemctl" enable --now "$unit"' in script
    assert 'disable) exec "$systemctl" disable --now "$unit"' in script
    assert "--property=ActiveState" in script
    assert "--property=SubState" in script
