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

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

import sys
from os import path
from calculate.core.server.func import Action,Tasks
from calculate.lib.cl_lang import setLocalTranslate,getLazyLocalTranslate
from calculate.lib.utils.files import FilesError, isMount
from calculate.desktop.desktop import DesktopError
from calculate.lib.cl_template import TemplatesError

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

class ClDesktopLogoutAction(Action):
    """
    Вывести пользователя из X сессии
    """
    # ошибки, которые отображаются без подробностей
    native_error = (FilesError,DesktopError,TemplatesError)

    successMessage = __("The user logged out from the session!")
    failedMessage = __("Unable to logout the user")
    interruptMessage = __("Logout manually interrupted")

    # список задач для действия
    tasks = [
         {'name':'user_logout',
          'method':'Desktop.userLogout(cl_desktop_login)',
         },
         {'name':'wait_logout',
          'message':__("Waiting for completion of the user logout"),
          'method':'Desktop.waitLogout(cl_desktop_login,300)'}
         ]

class ClDesktopAction(Action):
    """
    Настроить пользовательский профиль
    """
    # ошибки, которые отображаются без подробностей
    native_error = (FilesError,DesktopError,TemplatesError)

    successMessage = __("User account {ur_login} is configured")
    failedMessage = __("Failed to configure the user account")
    interruptMessage = __("Configuration manually interrupted")

    # список задач для действия
    tasks = [
         # создать домашниюю директорию
         {'name':'create_home',
          'message':__("Creating the home directory for {ur_login}"),
          'method':'Desktop.createUserDir(ur_login,ur_uid,ur_gid,ur_home_path)',
          'condition':lambda dv:not path.exists(dv.Get('ur_home_path'))
         },
         # подключить шифрованные данные
         {'name':'ecryptfs',
          'message':__("Mounting encrypted data"),
          'method':'Desktop.createCryptDir(ur_login,ur_uid,ur_gid,'
                                          'ur_home_path,False)',
          'condition':lambda dv:(not isMount(dv.Get('ur_home_path')) and \
                      dv.Get('ur_home_crypt_set') == 'on' and 
                      (not dv.isModuleInstalled("install") or
                      dv.Get('install.cl_autologin') != dv.Get('ur_login')))
         },
         # настроить пользовательских профиль шаблонами
         {'name':'user_profile',
          'message':__("Setting up the user profile"),
          'method':'Desktop.applyTemplates(None,False,'\
                   'False,None)',
          'condition':lambda Get: Get('cl_desktop_force_setup_set') == 'on' or \
                             Get('cl_desktop_update_profile_set') == 'on'
         },
         # отключить ресурсы подключенные в каталоге пользователя
         {'name':'umount_userres',
          'message': _("Unmouning user resources"),
          'method':'Desktop.umountUserRes(ur_mount_dirs)',
          'condition': lambda dv:dv.Get('ur_mount_dirs'),
          'depend': Tasks.failed()},
         {'name':'ecryptfs:umount_homedir',
          'method':'Desktop.umountUserRes(ur_home_path)',
          'depend': Tasks.failed()}
         ]
