# -*- coding: UTF-8 -*-
import re
import string
import tarfile
import os
import shutil
import resourceParse
import time
from common import *

# *************************************************************#
# 【函数名称】 _uninstallPatch
# 【功能说明】 卸载系统当前的热补丁
# 【参数】  beforeCheckDict：框架上下文字典
# 【返回值】  flag:(True：卸载成功，False：卸载失败),cliRet:原始信息
# *************************************************************#  
def _uninstallPatch(beforeCheckDict):
    upgradeErrMsg = ""

    #获取变量信息
    ssh = beforeCheckDict["ssh"]
    resource = beforeCheckDict["resource"]
    logger = beforeCheckDict["logger"]
    
    #使用Cli命令回滚热补丁
    cliRet = ssh.execCmd("rollbackhotpatch")
    if re.search("Are you sure", cliRet, re.IGNORECASE):
        cliRet1 = ssh.execCmd("y")
        if re.search("Succeeded", cliRet1, re.IGNORECASE):
            #卸载成功之后要睡眠一分钟
            time.sleep(60)
            logger.info("Uninstall state :"+str(True))
            ssh.execCmd("showupgradepkginfo -t 3")
            return (True, "")
    
    #卸载失败，休眠5秒再卸载一次
    time.sleep(5)
    cliRet = ssh.execCmd("rollbackhotpatch")
    if re.search("Are you sure", cliRet, re.IGNORECASE):
        cliRet1 = ssh.execCmd("y")
        if re.search("Succeeded", cliRet1, re.IGNORECASE):
            #卸载成功之后要睡眠一分钟
            time.sleep(60)
            ssh.execCmd("showupgradepkginfo -t 3")
            logger.info("Uninstall state :"+str(True))
            return (True, "")
    
    #回滚热补丁失败，返回错误
    upgradeErrMsg = resource.get('2029')
    ssh.execCmd("showupgradepkginfo -t 3")
    logger.info("Uninstall state :"+str(False))
    return (False, upgradeErrMsg)
    
# **************************************************************************** #
# 函数名称: 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
        
# *************************************************************#
# 【函数名称】     preFilter
# 【功能说明 】    安装补丁前过滤处理（详细描述：针对部分型号设备的部分系统版本，在打热补丁的时候需要卸载）
# 【参数】    dataDict：框架上下文
# 【返回值】    flag：过滤处理是否成功标志（True：过滤处理成功，False：过滤处理失败），errMsg：错误消息
# *************************************************************#    
def preFilter(dataDict):
    curHotPatch = dataDict["curHotPatchVer"] #当前设备的热补丁
    #全局变量定义
    flag = True
    errMsg = ""
    logger = dataDict["logger"]
    installHotPatchVer = dataDict["installHotPatchVer"]#需要安装的热补丁
    ssh = dataDict["ssh"]
    curDevType = getCurDeviceType(ssh) #当前设备版本
    curSysVersion = getCurSystemVersion(ssh)#当前升级系统版本
    logger.info("=[preInstallHotPatchHandle] begin=")
    logger.info("[preInstallHotPatchHandle] Current info:(curHotPatch)\
        " + curHotPatch+",(installHotPatch)"+installHotPatchVer+",(curDev)"+curDevType+",(curSys)"+curSysVersion)
    
    #需要特殊操作的设备类型列表
    devTypeList = ["S3900-M200", "S3900-M300", "S5900-M100", "S5900-M200", "S6900-M100"]
    #需要特殊操作的系统版本列表
    systemVerList = ["V100R002C00SPC011","V100R002C00SPC012","V100R002C00SPC013","V100R002C00SPC015","V100R002C00SPCg00"]
    #需要执行升级的系统版本和的补丁的关系字典
    needInstallPatchMap = {"V100R002C00SPC011":"V100R002C00SPHb05",
                            "V100R002C00SPC012":"V100R002C00SPHc05",
                            "V100R002C00SPC013":"V100R002C00SPHd02", 
                            "V100R002C00SPC015":"V100R002C00SPHf03",
                            "V100R002C00SPCg00":"V100R002C00SPHg03"}
    
    #升级前需要卸载补丁和系统版本的关系字典
    uninstallPatchMap = {"V100R002C00SPC011":"V100R002C00SPHb04",
                         "V100R002C00SPC012":"V100R002C00SPHc04",
                         "V100R002C00SPC013":"V100R002C00SPHd01",
                         "V100R002C00SPC015":"V100R002C00SPHf02",
                         "V100R002C00SPCg00":"V100R002C00SPHg02"}
    
    #设备型号不在过滤列表中，直接通过
    if curDevType not in devTypeList:
        return True,errMsg
    logger.info("Current devType("+curDevType+") in devList ")
    
    #当前系统版本不在列表中,直接通过
    if curSysVersion not in systemVerList:
        return True,errMsg
    logger.info("Current systemVersion("+curSysVersion+") in sysVerList ")
    
    #当前设备不存在补丁，不需要过滤，直接通过
    if not curHotPatch:
        return True,errMsg
    logger.info("Current systemVersion("+curSysVersion+") exsists hotpatch("+curHotPatch+")")
    
    #格式化当前热补丁版本:去掉热补丁版本号中的SPCXXX
    curHotPatch = switchHotPatchVersion(curHotPatch)
    
    #满足过滤情况（设备型号，系统型号都满足过滤条件，同时系统存在热补丁）的处理###
    #>>当前热补丁已经为最新，不需要升级
    needInstallHotPatch = needInstallPatchMap.get(curSysVersion)#需要安装的补丁
    if needInstallHotPatch == curHotPatch:
        logger.info("Current hotpatch ("+needInstallHotPatch+") is the latest")
        return True,errMsg
    
    #>>当前热补丁不是最新的，需要再判断处理
    else:
      needUninstallPatch = uninstallPatchMap.get(curSysVersion) #当前需要卸载的补丁
      #当前系统补丁不需要卸载
      if needUninstallPatch != curHotPatch:
          logger.info("Current hotpatch ("+curHotPatch+") mustn't be uninstalled")
          return True,errMsg
      #卸载补丁
      logger.info("Uninstall hotpatch("+curHotPatch+") begin")
      isUninstallSuccess,errMsg = _uninstallPatch(dataDict)
      logger.info("Uninstall ("+curHotPatch+") end")
      #卸载失败，流程停止
      if not isUninstallSuccess:
          logger.info("Uninstall old hotpatch(" + curHotPatch + ")  faild!")
          return False,errMsg
      #卸载成功，流程通过    
      else:
          logger.info("Uninstall old hotpatch:"+needUninstallPatch+" success!")
          return True,errMsg
      #升级流程继续
