#!/usr/bin/python
#
# pyTES_Upgrade.py
# Copyright (C) 2017 eabeda <elyes.abeda@gmail.com>
# 
# pyTES is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# pyTES is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.

"""
Libraries
"""
try:
    '''
    System
    '''
    import os
    import sys
    '''
    Configuration
    '''
    from pyTES_Conf import *
    '''
    Define
    '''
    from pyTES_Define import *
    '''
    Functions
    '''
    from pyTES_Display import *
    from pyTES_Exec import *
    from pyTES_System import *
    
except Exception as e:
    _sys_exc_type, _sys_exc_obj, _sys_exc_tb = sys.exc_info()
    _filename = _sys_exc_tb.tb_frame.f_code.co_filename
    _line = _sys_exc_tb.tb_lineno
    _e_name = _sys_exc_type.__name__
    _e_message = _sys_exc_obj
    print("%s:%d => %s: '%s' (Please setup your system)" % (_filename, _line, _e_name, _e_message))
    sys.exit(e)
finally:
    pass

"""
Class: pyTES_Upgrade
    Attributes:
        m_check_upgrade_command
        m_force_upgrade_command
        m_url_upgrade_command
        m_targets
        m_expected_result
        m_execClient
    Methods:
        __init__()
        checkUpgrade()
        startUpgrade()
        startUpgradeViaUrl()

""" 
class pyTES_Upgrade:
    """
    __init__(): constructs and inits pyTES_Upgrade
        takes: _output_folder
        returns: None
    """
    def __init__(self, _output_folder):
        try:
            '''
            configuration parameters
            '''
            self.m_output_folder = _output_folder
            self.m_check_upgrade_command = {'cmd': PYTES_CONF_CHECK_UPGRADE_COMMAND}
            self.m_force_upgrade_command = {'cmd': PYTES_CONF_FORCE_UPGRADE_COMMAND}
            self.m_url_upgrade_command = {'cmd': PYTES_CONF_URL_UPGRADE_COMMAND}
            self.m_targets = {'type': PYTES_OBJ_DEVICE}
            self.m_expected_result = {'value': "", 'type': PYTES_OBJ_PATTERN}
            """
            instantiation of pyTES_Exec
            """
            self.m_execClient = pyTES_Exec(self.m_output_folder)
            '''
            create output_upgrade.log
            '''
            self.m_execClient._output_tc_execution_filename = self.m_output_folder + '/' + PYTES_CONF_UPGRADE_OUTPUT_EXECUTION_FILE
            self.m_execClient.writeToOutputFile(self.m_execClient._output_tc_execution_filename, "###### Upgrade ######\n")
            
        except Exception as e:
            _filename, _function, _line, _e_name, _e_message = getExecutionInfos()
            Display1("%s:%d|%s() => %s: '%s'" % (_filename, _line, _function, _e_name, _e_message), PYTES_COLOR_COMMON_EXCEPTION)
            sys.exit(PYTES_ERRCODE_EXCEPTION_ERROR)
        finally:
            pass

    """
    checkUpgrade(): checks for upgrading
        takes: None
        returns: _output_upgrade_command
    """
    def checkUpgrade(self):
        try:
            '''
            initialization
            '''
            _output_upgrade_command = None
            _step_name = sys._getframe().f_code.co_name
            '''
            checking
            '''
            self.m_execClient.Log1("\t\t" + "Step '%s':" % (_step_name), PYTES_COLOR_UPGRADE_NOTICE)
            _result_of_upgrade_command = self.m_execClient.executeActionOfStepRemotely(self.m_targets, self.m_check_upgrade_command, self.m_expected_result)
            #Debug(_result_of_upgrade_command)
            '''
            display result of Upgrade
            '''
            self.m_execClient.displayGlobalResultOfCurrentStep(_step_name, _result_of_upgrade_command)
            
        except Exception as e:
            _filename, _function, _line, _e_name, _e_message = getExecutionInfos()
            Display1("%s:%d|%s() => %s: '%s'" % (_filename, _line, _function, _e_name, _e_message), PYTES_COLOR_COMMON_EXCEPTION)
            sys.exit(PYTES_ERRCODE_EXCEPTION_ERROR)
        finally:
            return _output_upgrade_command
        
    """
    startUpgrade(): starts forcing upgrade
        takes: None
        returns: _output_upgrade_command
    """
    def startUpgrade(self):
        try:
            '''
            initialization
            '''
            _output_upgrade_command = None
            _step_name = sys._getframe().f_code.co_name
            '''
            upgrading
            '''
            self.m_execClient.Log1("\t\t" + "Step '%s':" % (_step_name), PYTES_COLOR_UPGRADE_NOTICE)
            _result_of_upgrade_command = self.m_execClient.executeActionOfStepRemotely(self.m_targets, self.m_force_upgrade_command, self.m_expected_result)
            #Debug(_result_of_upgrade_command)
            '''
            display result of Upgrade
            '''
            self.m_execClient.displayGlobalResultOfCurrentStep(_step_name, _result_of_upgrade_command)
            
        except Exception as e:
            _filename, _function, _line, _e_name, _e_message = getExecutionInfos()
            Display1("%s:%d|%s() => %s: '%s'" % (_filename, _line, _function, _e_name, _e_message), PYTES_COLOR_COMMON_EXCEPTION)
            sys.exit(PYTES_ERRCODE_EXCEPTION_ERROR)
        finally:
            return _output_upgrade_command
        
    """
    startUpgradeViaUrl(): starts upgrading via URL
        takes: build_path
        returns: _output_upgrade_command
    """
    def startUpgradeViaUrl(self, build_path=""):
        try:
            '''
            initialization
            '''
            _output_upgrade_command = None
            self.m_url_upgrade_command = {'cmd': self.m_url_upgrade_command['cmd'] + build_path}
            _step_name = sys._getframe().f_code.co_name
            '''
            upgrading via url
            '''
            self.m_execClient.Log1("\t\t" + "Step '%s':" % (_step_name), PYTES_COLOR_UPGRADE_NOTICE)
            _result_of_upgrade_command = self.m_execClient.executeActionOfStepRemotely(self.m_targets, self.m_url_upgrade_command, self.m_expected_result)
            #Debug(_result_of_upgrade_command)
            '''
            display result of Upgrade
            '''
            self.m_execClient.displayGlobalResultOfCurrentStep(_step_name, _result_of_upgrade_command)
            
        except Exception as e:
            _filename, _function, _line, _e_name, _e_message = getExecutionInfos()
            Display1("%s:%d|%s() => %s: '%s'" % (_filename, _line, _function, _e_name, _e_message), PYTES_COLOR_COMMON_EXCEPTION)
            sys.exit(PYTES_ERRCODE_EXCEPTION_ERROR)
        finally:
            return _output_upgrade_command
        
'''
variables
'''
_build_path = "build#101"

"""
Function: main
    takes: scriptname, argv
    returns: None
""" 
def main(scriptname, argv):
    try:
        '''
        initialization
        '''
        _tu_name = "TestUnit_pyTES_Upgrade"
        _tu_entity = "========== %s ==========\n" % (_tu_name)
        _output_folder = PYTES_CONF_OUTPUT_FOLDER + '/' + _tu_name
        '''
        create output folder
        '''
        _created = createDirectory(_output_folder)
        #Debug(_created)
        '''
        instantiation of pyTES_Upgrade
        '''
        _upgradeClient = pyTES_Upgrade(_output_folder)
        '''
        upgrading
        '''
        _check_upgarde = _upgradeClient.checkUpgrade()
        #Debug(_check_upgarde)
        _start_upgrade = _upgradeClient.startUpgrade()
        #Debug(_start_upgrade)
        _start_url_upgrade = _upgradeClient.startUpgradeViaUrl(_build_path)
        #Debug(_start_url_upgrade)
        
    except SystemExit as e:
        sys.exit(e)
    except Exception as e:
        _filename, _function, _line, _e_name, _e_message = getExecutionInfos()
        Display1("%s:%d|%s() => %s: '%s'" % (_filename, _line, _function, _e_name, _e_message), PYTES_COLOR_COMMON_EXCEPTION)
        sys.exit(PYTES_ERRCODE_EXCEPTION_ERROR)
    except:
        _filename, _function, _line, _e_name, _e_message = getExecutionInfos()
        Display1("%s:%d|%s() => %s: '%s'" % (_filename, _line, _function, _e_name, _e_message), PYTES_COLOR_COMMON_EXCEPTION)
        sys.exit(PYTES_ERRCODE_UNKNOWN_ERROR)
    finally:
        sys.exit(PYTES_ERRCODE_NO_ERROR)

if __name__ == "__main__":
    main(sys.argv[0], sys.argv[1:])
    