#-*- 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.

import os
from os import path
import re
import sys
import pwd
import time
import traceback

from datavars import DataVarsUpdate, DataVars, __version__,__app__

from calculate.lib.cl_template import Template, ProgressTemplate,TemplatesError
from calculate.lib.utils.files import runOsCommand, isMount
from calculate.lib.utils.common import getpathenv,appendProgramToEnvFile, \
                                       removeProgramToEnvFile
from calculate.core.server.func import safetyWrapper

from calculate.lib.cl_lang import setLocalTranslate,getLazyLocalTranslate
setLocalTranslate('cl_update3',sys.modules[__name__])
__ = getLazyLocalTranslate(_)

class UpdateError(Exception):
    """Update Error"""

class Update:
    """
    Update logic object

    Has fundamental method update for system update
    """
    
    def __init__(self):
        self.homeDir = ""
        self.clTempl = None
        self.clVars = None

    def applyTemplates(self):
        """Apply templates for user"""
        if self.clTempl:
            self.closeClTemplate()
        self.clVars.Set("cl_chroot_path","/", True)
        self.clVars.Set("cl_merge_set","on",True)
        self.clTempl = ProgressTemplate(self.setProgress,self.clVars,
                                        cltObj=True,cltFilter=True,
                                        printSUCCESS=self.printSUCCESS,
                                        printWARNING=self.printWARNING,
                                        askConfirm=self.askConfirm,
                                        dispatchConf=self.dispatchConf,
                                        printERROR=self.printERROR)
        dirsFiles = self.clTempl.applyTemplates()
        if self.clTempl.getError():
            self.printERROR(self.clTempl.getError().strip())
            return False
        else:
            return dirsFiles

    def initVars(self,datavars=None):
        """Primary variables initialization"""
        if not datavars:
            self.clVars = DataVarsDesktop()
            self.clVars.importDesktop()
            self.clVars.flIniFile()
        else:
            self.clVars = datavars

    def closeClTemplate(self,*args):
        if self.clTempl:
            if self.clTempl.cltObj:
                self.clTempl.cltObj.closeFiles()
            self.clTempl.closeFiles()
            self.clTempl = None

    @safetyWrapper(native_errors=(TemplatesError,UpdateError),
                   man_int=__("Update manually interrupted"),
                   post_action=closeClTemplate,
                   success_message=__("Update finished!"))
    def update(self, datavars=None):
        """
        Creating user profile and userdir
        """
        self.initVars(datavars)
        return bool(self.applyTemplates())
