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

# Copyright 2010 Calculate Ltd. 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.

from update_config.cl_update_config import __app__, __version__,\
                                        updateSystemConfigs, updateUserConfigs
from cl_print import color_print as old_color_print
from cl_opt import opt
import sys

import cl_lang
# Перевод модуля
tr = cl_lang.lang()
tr.setLocalDomain('cl_lib')
tr.setLanguage(sys.modules[__name__])

# Использование программы
USAGE = _("%prog [options] package_name")

# Коментарии к использованию программы
COMMENT_EXAMPLES = _("Update configuration files of package nss_ldap")

# Пример использования программы
EXAMPLES = _(r"%prog --system --pkg_category net-nds --pkg_version 2.4.19\
  --path / openldap")

# Описание программы (что делает программа)
DESCRIPTION = _("Update configuration files package installed")

# Опции командной строки
CMD_OPTIONS=[{'longOption':"system",
              'help':_("update system configuration files")},
             {'longOption':"desktop",
              'help':_("update desktop (user) configuration files")},
             {'longOption':"path",
              'optVal':"PATH",
              'help':_("root path for saving the updated configuration files")},
              {'longOption':"pkg_category",
              'optVal':"CATEGORY",
              'help':_("package category name")},
              {'longOption':"pkg_version",
              'optVal':"VERSION",
              'help':_("package version number without the revision")}]

class update_cmd:
    def __init__(self):
        # Объект опций командной строки
        self.optobj = opt(\
            package=__app__,
            version=__version__,
            usage=USAGE,
            examples=EXAMPLES,
            comment_examples=COMMENT_EXAMPLES,
            description=DESCRIPTION,
            option_list=CMD_OPTIONS + opt.color_control,
            check_values=self.checkOpts)
        # Создаем объекты логики
        self.logicSystemObj = updateSystemConfigs()
        self.logicUserObj = updateUserConfigs()


    def setPrintNoColor(self, optObj):
        """Установка печати сообщений без цвета"""
        if optObj.color and optObj.color=="never":
            old_color_print.colorPrint = lambda *arg: \
                                                   sys.stdout.write(arg[-1]) or\
                                                   sys.stdout.flush()

    def checkOpts(self, optObj, args):
        """Проверка опций командной строки"""
        if not args:
            errMsg = _("no such argument") + ":" + " %s" %USAGE.split(" ")[-1]
            self.optobj.error(errMsg)
            return False
        if len(args)>1:
            errMsg = _("incorrect argument") + ":" + " %s" %" ".join(args)
            self.optobj.error(errMsg)
            return False
        if optObj.system and not optObj.path:
            errMsg = _("no such option") + ":" + " --path"
            self.optobj.error(errMsg)
            return False
        if not optObj.pkg_category:
            errMsg = _("no such option") + ":" + " --pkg_category"
            self.optobj.error(errMsg)
            return False
        if not optObj.pkg_version:
            errMsg = _("no such option") + ":" + " --pkg_version"
            self.optobj.error(errMsg)
            return False
        if not filter(lambda x: x, [optObj.system, optObj.desktop]):
            errMsg = _("no such options") + ":" + " --system " + _("or") +\
                                        " --desktop"
            self.optobj.error(errMsg)
            return False
        return optObj, args

    def updateSystemConfig(self, nameProgram, category, version, configPath):
        """Обновление системных конфигурационных файлов"""
        if not self.logicSystemObj.updateConfig(nameProgram, category, version,
                                                configPath):
            return False
        return True

    def updateUserConfig(self, nameProgram, category, version):
        """Обновление конфигурационных файлов для пользователей в X сеансах"""
        if not self.logicUserObj.updateConfig(nameProgram, category, version):
            return False
        return True