
from __future__ import absolute_import
from __future__ import division

import os

from . import commands
from . import supervdsm

SYSTEMCTL = "/usr/bin/systemctl"


def stop(pattern):
    if os.geteuid() != 0:
        return supervdsm.getProxy().systemctl_stop(pattern)

    return commands.run([SYSTEMCTL, 'stop', pattern])


def show(pattern=None, properties=()):
    cmd = [SYSTEMCTL, "show"]

    if properties:
        keys = ",".join(properties)
        cmd.append("--property=" + keys)

    if pattern:
        cmd.append(pattern)

    out = commands.run(cmd).decode("utf-8")
    return _parse_properties(out)


def _parse_properties(out):
    out = out.strip()
    if not out:
        return []

    return [dict(pair.split("=", 1) for pair in unit.split("\n"))
            for unit in out.split("\n\n")]
