# -*- coding: UTF-8 -*-

import os
import shutil
import resourceParse
import common

from cbb.frame.util.tar_util import decompress_tar_special_file

logger = None

# *************************************************************#
# 函数名称: getHotPatchPKGVersion
# 功能说明: 解压热补丁包的配置文件，获取热补丁包版本号配套关系
# 其 他   :  无
# *************************************************************#  
def getHotPatchPKGVersion(filePath):
    
    hotPatchPkgVersion = ""
    SysVersionSupported = ""
    SysVersionBSupported = ""

    extractPath = filePath[0: filePath.index('.tgz')]
    
    try:
        # 查看热补丁包是否有效
        # 普通热补丁包：patch.conf文件在第一层压缩目录下
        # 补丁包无效，直接返回为空
        success, _ = decompress_tar_special_file(filePath, extractPath, 'patch.conf')
        if not success:
            return "", "", ""
    
        #解析补丁配置文件
        confFile = extractPath + os.sep + 'patch.conf'
        conFileFd = open(confFile, "r")
        confInfo = conFileFd.read()
        #关闭文件句柄
        conFileFd.close()
        lineList = confInfo.splitlines()
        
        #获取配置文件中的热补丁版本号
        for line in lineList:
    
            field = line.split()
            if len(field) < 2:
                continue
            #获取版本配置信息
            if field[0] == "Version":
                hotPatchPkgVersion = field[1]
            elif field[0] == "SysVersionSupported":
                SysVersionSupported = field[1]
            elif field[0] == "SysVersionBSupported":
                SysVersionBSupported = common.switchValidVersion(field[1])
            else:
                continue
    except Exception as e:
        if logger and hasattr(logger, "error"):
            logger.error(str(e))
    finally:
        shutil.rmtree(filePath[0:-4], ignore_errors=True)
    
    return (hotPatchPkgVersion, SysVersionSupported, SysVersionBSupported)

# *************************************************************#
# 函数名称: checkProductType
# 功能说明: 查询设备类型是否匹配
# 其 他   :  无
# *************************************************************#  
def checkProductType(productType, deviceType):
    
    checkFlag = False
    
    #通过设备类型查询是否匹配
    #第一位代表T系列V1产品，第二位第三位组合代表设备型号：10：S2900、18：S3900、20：S6900
    if productType == "110":
        if deviceType in ["S2200T", "S2200T-S", "S2600T", "S2900"]:
            checkFlag = True
    elif productType == "118":
        if deviceType in ["S3900-M200", "S3900-M300", "S5500T"]:
            checkFlag = True
    elif productType == "120":
        if deviceType in ["S5600T", "S5900-M100", "S5800T", "S5900-M200", "S6800T", "S6900-M100", "S8000-I"]:
            checkFlag = True
    else:
        pass
    
    return checkFlag

# *************************************************************#
# 函数名称: getDescHotPatchVersion
# 功能说明: 拼装热补丁包显示版本号信息
# 其 他   :  无
# *************************************************************#
def getDescHotPatchVersion(deviceType, systemVersion, hotPatchVersion):
    
    #组装后格式为：OceanStor S2600T V100R005C01SPH701
    descVersion = "OceanStor " + deviceType + " " \
        + systemVersion[0:11] + hotPatchVersion
    
    return descVersion

# *************************************************************#
# 函数名称: execute
# 功能说明: 解析热补丁包所在路径，返回字典：热补丁版本号+对应的文件名(入口函数)
# 其 他   :  无
# *************************************************************#
def execute(dataDict):

    ssh = dataDict.get("ssh")
    lang = dataDict.get("lang")
    global logger
    logger = dataDict.get("logger")

    dev = dataDict.get("dev")
    deviceType = str(dev.getDeviceType())
    systemVersion = dev.getProductVersion()

    hotPatchTgzPkgName = dataDict['packagePath']
    
    checkDict = {}
    #解析resource文件并保存
    resource = resourceParse.execute(lang)
    dataDict["resource"] = resource
    
    #版本号规范化转换
    systemVersion = common.switchValidVersion(systemVersion)
    
    #获取热补丁版本号
    iRet = getHotPatchPKGVersion(hotPatchTgzPkgName)
    pkgVersion = iRet[0]
    pkgSystemVerComp = iRet[1]
    pkgSystemSpcVerComp = iRet[2]
    
    #包有效性校验
    if pkgVersion == "":
        errMsg = resource.get('1002')
        return (False, errMsg, checkDict)
    #补丁包兼容性校验
    if pkgSystemVerComp != "" and len(pkgSystemVerComp) == 10:
        productType = pkgSystemVerComp[0:3]
        checkFlag = checkProductType(productType, deviceType)
        if not checkFlag:
           errMsg = resource.get('2008')
           return (False, errMsg, checkDict)
    else:
        errMsg = resource.get('1002')
        return (False, errMsg, checkDict)
        
    #检查SPC版本兼容性:V100R005C00SPC700
    if pkgSystemSpcVerComp != "" and len(pkgSystemSpcVerComp) == 17:
        if systemVersion != pkgSystemSpcVerComp:
           errMsg = resource.get('2008')
           return (False, errMsg, checkDict)
    
    #设置显示的热补丁包信息
    hotPatchVersionDesc = getDescHotPatchVersion(deviceType, systemVersion, pkgVersion)
    
    checkDict = {"hotPatchVersion": hotPatchVersionDesc}
    
    #检查结果返回
    return (True, "", checkDict)
