# -*- coding: utf-8 -*-

# Copyright 2016 Mir Calculate. http://www.calculate-linux.org
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import sys
from calculate.core.server.func import MethodsInterface
from calculate.lib.utils.openrc import OpenRC, OpenRCError
from calculate.lib.configparser import (ConfigParserCaseSensLocked,
                                        Error as ConfigParserError)
import os
from os import path

_ = lambda x: x
from calculate.lib.cl_lang import (setLocalTranslate, getLazyLocalTranslate)

setLocalTranslate('cl_server3', sys.modules[__name__])
__ = getLazyLocalTranslate(_)


class ServerError(Exception):
    pass


class Server(MethodsInterface):
    """Базовый объект для настройки сервисов

    """

    class Method(object):
        Backup = "server_backup"
        All = (Backup,)

    def init(self):
        pass

    def set_server_action(self, action):
        self.clVars.Set('cl_action', action, force=True)
        return True

    def stop_service(self, service):
        try:
            OpenRC().stop(service)
            return True
        except OpenRCError:
            return False

    def start_service(self, service):
        try:
            OpenRC().start(service)
            return True
        except OpenRCError as e:
            # self.printERROR(str(e))
            return False

    def restart_service(self, service):
        return self.stop_service(service) and self.start_service(service)

    def autorun_enable(self, service):
        try:
            OpenRC().add_default(service)
            return True
        except OpenRCError as e:
            self.printERROR(str(e))

    def autorun_disable(self, service):
        try:
            OpenRC().del_default(service)
            return True
        except OpenRCError as e:
            return False

    def save_service_data(self, service, binddn, cred):
        """
        Сохранить данные сервиса
        :param service:
        :param binddn:
        :param cred:
        :return:
        """
        cp_path = self.clVars.Get('server.cl_server_env_path')
        cp = ConfigParserCaseSensLocked(cp_path)
        try:
            with cp.lock_write() as cp:
                if service not in cp:
                    cp.add_section(service)
                cp[service]["DN"] = binddn
                cp[service]["PASS"] = cred
        except ConfigParserError:
            raise ServerError(_("Failed to save server parameters"))
        return True

    def clear_service_data(self, service):
        """
        Удалить данные настроенного сервера или все данные
        :param service: сервис или all
        :return:
        """
        cp_path = self.clVars.Get('server.cl_server_env_path')
        if service == "all":
            try:
                if path.exists(cp_path):
                    os.unlink(cp_path)
            except OSError:
                raise ServerError(_("Failed to clear server configuration"))

        cp = ConfigParserCaseSensLocked(cp_path)
        try:
            with cp.lock_write() as cp:
                if service in cp:
                    cp.remove_section(service)
        except ConfigParserError:
            raise ServerError(_("Failed to remove server parameters"))
        return True

    def service_install(self, service):
        self.clVars.Write('sr_%s_set' % service, 'on', header="server")
        return True

    def service_uninstall(self, service):
        self.clVars.Write('sr_%s_set' % service, 'off', header="server")
        return True
