#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# === This file is part of Calamares - <https://calamares.io> ===
#
#   SPDX-FileCopyrightText: 2016 Artoo <artoo@manjaro.org>
#   SPDX-FileCopyrightText: 2017 Philip Müller <philm@manjaro.org>
#   SPDX-FileCopyrightText: 2018 Artoo <artoo@artixlinux.org>
#   SPDX-FileCopyrightText: 2018-2019 Adriaan de Groot <groot@kde.org>
#   SPDX-FileCopyrightText: 2023-2024 Artoo <artoo@artixlinux.org>
#   SPDX-License-Identifier: GPL-3.0-or-later
#
#   Calamares is Free Software: see the License-Identifier above.
#

import libcalamares

import gettext
_ = gettext.translation("calamares-python",
                        localedir=libcalamares.utils.gettext_path(),
                        languages=libcalamares.utils.gettext_languages(),
                        fallback=True).gettext


def pretty_name():
    return _("Configure services")


def manage_services(services, cmd):
    """
    For each entry in @p services, run "<command> <action> <name>",
    where each service is a mapping of service name, action, and a flag.

    Returns a failure message, or None if this was successful.
    Services that are not mandatory have their failures suppressed
    silently.
    """
    for sv in services:
        if isinstance(sv, str):
            name = sv
            action = "enable"
            mandatory = False
        else:
            if "name" not in sv:
                libcalamares.utils.error("The key 'name' is missing from the mapping {_sv!s}. Continuing to the next service.".format(_sv=str(sv)))
                continue
            name = sv["name"]
            action = sv.get("action", "enable")
            mandatory = sv.get("mandatory", False)

        command = [ cmd ]

        args = [action, name]

        command.extend(args)

        libcalamares.utils.debug("Manager command: {!s}".format(command))

        ec = libcalamares.utils.target_env_call(command)

        if ec != 0:
            libcalamares.utils.warning(
                "Cannot {} service {}".format(action, name)
            )
            libcalamares.utils.warning(
                "service {} call in chroot returned error code {}".format(action, ec)
            )
            if mandatory:
                title = _("Cannot modify service")
                diagnostic = _("<code>service {_action!s}</code> call in chroot returned error code {_ec!s}.").format(_action=action, _ec=ec)
                description = _("Cannot {_action!s} service <code>{_name!s}</code>.").format(_action=action, _name=name)
                return (
                    title,
                    description + " " + diagnostic
                )


def run():
    """
    Setup services
    """
    cmd = libcalamares.job.configuration.get("command")

    services = libcalamares.job.configuration.get("services", [])

    r = manage_services(services, cmd)
    if r is not None:
        return r

