import subprocess
from typing import List, Optional


def _escape(unit: str) -> str:
    # NOTE: https://www.freedesktop.org/software/systemd/man/systemd-escape.html#Options
    out: bytes = subprocess.check_output(["systemd-escape", "--mangle", unit])
    return out.decode().replace("\n", "")


def start(unit: str) -> str:
    systemctl_out = subprocess.check_output(["systemctl", "start", unit])
    return systemctl_out.decode()


def stop(unit: str) -> str:
    systemctl_out = subprocess.check_output(
        ["systemctl", "stop", _escape(unit)]
    )
    return systemctl_out.decode()


def enable(unit: str, now: Optional[bool] = False) -> str:
    systemctl_cmd: List[str]
    if now:
        systemctl_cmd = ["systemctl", "enable", "--now", _escape(unit)]

    else:
        systemctl_cmd = ["systemctl", "enable", _escape(unit)]

    systemctl_out: bytes = subprocess.check_output(systemctl_cmd)
    return systemctl_out.decode()


def disable(unit: str, now: Optional[bool] = False) -> str:
    systemctl_cmd: List[str]
    if now:
        systemctl_cmd = ["systemctl", "disable", "--now", _escape(unit)]

    else:
        systemctl_cmd = ["systemctl", "disable", _escape(unit)]

    systemctl_out: bytes = subprocess.check_output(systemctl_cmd)
    return systemctl_out.decode()


def status(unit: str) -> str:
    systemctl_out: bytes
    # NOTE: we're not using check output as it raises an error in case of non-zero return code; instead we use an
    # equivalent.
    # See: https://docs.python.org/3/library/subprocess.html#subprocess.check_output
    systemctl_out = subprocess.run(
        ["systemctl", "status", _escape(unit)],
        check=False,
        stdout=subprocess.PIPE,
    ).stdout
    return systemctl_out.decode()
