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

import re

# **************************************************************************** #
# 函数名称: switchHotPatchVersion
# 功能说明: 将热补丁版本号转化成有效的版本号（V100R002C00SPC011SPHb04转变成V100R002C00SPHb04）
# 输入参数: version
# 输出参数: 无
# 返 回 值: version
# **************************************************************************** # 
def switchHotPatchVersion(version):
    
    startIndex = version.index("V100")
    #提取有效的版本号信息
    version = version[startIndex:]

    #老版本热补丁版本不规范：V100R002C00SPC011SPHb04
    if "SPC" in version:
        startIndex = version.index("SPC")
        endIndex = startIndex + 6
        delStr = version[startIndex: endIndex]
        version = version.replace(delStr, "")
    return version

# *************************************************************#
# 函数名称: execute
# 功能说明: 查询当前设备已安装热补丁
# 其 他   :  无
# *************************************************************#
def execute(dataDict):

    #查询当前设备已安装热补丁
    ssh = dataDict.get("ssh")
    curHotPatchVer = ""

    hotPatchVerInfo = ssh.execCmd("showupgradepkginfo -t 3")
    #不支持热补丁，检查通过
    if re.search("not exist.|Error : Invalid argument", hotPatchVerInfo, re.IGNORECASE):
        return (True, '')

    #没有安装任何热补丁，返回空
    if re.search("command operates successfully", hotPatchVerInfo, re.IGNORECASE):
        return (True, '')

    #导入了热补丁包但是没有激活
    if not re.search("Running", hotPatchVerInfo, re.IGNORECASE):
        return (True, '')
    
    lineList = hotPatchVerInfo.splitlines()
    #信息少于7行，查询信息失败
    if len(lineList) < 7:
        return (False, '')
    
    #正常情况下获取Running的热补丁版本
    for line in lineList:
        if re.search("A|B", line) and re.search("Running", line, re.IGNORECASE):
            field = line.split()
            if len(field) >= 2:
                curHotPatchVer = switchHotPatchVersion(field[1])
                break
        else:
            continue 

    #检查结果返回
    return (True, curHotPatchVer)
    
