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

from common import resourceParse
from common.baseFactory import log
from frame.cli import cliUtil
from frame.base import config
from common import cliUtils
from utils import Products

DEVICE_TYPE = "2600 V3 for Video"
# 支持NAS的版本号：V300R006C20及之后版本；之前的版本支持NoNAS
PATCH_KEY_FOR_26_V_VER_RANGE = ["V300R006C20", "V300R006C60"]
PATCH_KEY_FOR_26_V_VER_DICT = {"V300R006C20": "V300R006C20SPH030",
                               "V300R006C50SPC100": "V300R006C50SPH125"}


def execute(data_dict):
    """
    检查方法：
    步骤1、获取当前设备的型号及版本号；
    步骤2、执行命令show file_system general；

    检查标准：
    1.若当前设备型号为2600 V3 for Video，且版本号V300R006C20及之后版本,
        V300R006C60之前版本（不含），继续检查；否则检查通过；
    2.若当前设备没有安装补丁，则检查通过；否则继续检查；
    3.若步骤2的执行结果中存在记录，则存在文件系统，检查不通过；
    """
    return FSConfigCheck(data_dict).check()


class FSConfigCheck:
    def __init__(self, data_dict):
        self.data_dict = data_dict
        self.cli = self.data_dict.get("ssh")
        self.lang = data_dict.get('lang')
        self.resource = resourceParse.execute(self.lang)
        self.dev = self.data_dict.get("dev")
        self.dev_type = str(self.dev.getDeviceType())
        self.product_version = self.dev.getProductVersion()
        self.product_hotpatch = self.dev.getHotPatchVersion()
        self.pkg_patch_ver = data_dict.get("pkgVersion")

    def check(self):
        log.info(self.data_dict,
                 "current device type:{},current product version:{} pkg_patch_ver:{}"
                 .format(self.dev_type, self.product_version,
                         self.pkg_patch_ver))
        # 当前设备型号为2600 V3 for Video
        if self.dev_type != DEVICE_TYPE:
            return True, "", ""
        # 1、系统版本不为V300R006C20和V300R006C50SPC100版本，检查通过
        if self.product_version not in PATCH_KEY_FOR_26_V_VER_DICT.keys():
            return True, "", ""
        # 2、若输入待安装的补丁版本为V300R006C50SPH125及之后补丁，或者V300R006C20SPH030及之后补丁，则检查通过；否则检查不通过；
        if Products.compareVersion(self.pkg_patch_ver,
                                   PATCH_KEY_FOR_26_V_VER_DICT.get(
                                           self.product_version)) >= 0:
            return True, "", ""
        else:
            err_msg = self.resource.get(
                "FSConfigCheck.file.system.config.tip").format(
                self.product_version, self.product_hotpatch,
                PATCH_KEY_FOR_26_V_VER_DICT.get(self.product_version))
            return False, err_msg, ""

    def get_patch_key(self):
        patch_key = self.get_patch_key_by_version()
        log.info(self.data_dict,
                 "By version The patch key is:%s" % patch_key)
        if patch_key:
            return True, "", "", patch_key

        # 查询是否安装NAS补丁。如果是NAS则安装NAS,否则继续检查文件系统
        patch_key, err_key, cli_ret = self.check_install_nas_patch()
        log.info(self.data_dict,
                 "By installed NAS Patch The patch key is:%s and err_key is:%s"
                 % (patch_key, err_key))
        if not patch_key:
            return False, err_key, cli_ret, patch_key

        if patch_key == config.PatchKey.NAS:
            return True, "", cli_ret, config.PatchKey.NAS

        # 检查是否安装文件系统，安装则报错，没有安装则返回No-nas
        patch_key, err_key, cli_ret = self.get_patch_key_by_file_system()
        log.info(self.data_dict,
                 "By file system The patch key is:%s and err_key is:%s"
                 % (patch_key, err_key))
        if not patch_key:
            return False, err_key, cli_ret, patch_key
        return True, "", "", patch_key

    def get_new_patch_key(self):
        log.info(self.data_dict,
                 "current device type:{},current product version:{} product_hotpatch:{}"
                 .format(self.dev_type, self.product_version,
                         self.product_hotpatch))
        # 1、未安装补丁
        if not self.product_hotpatch or self.product_hotpatch == "--":
            return True, "", "", config.PatchKey.NO_NAS
        # 2、.V300R006C50SPC100安装了SPH125或之后补丁，或者V300R006C20安装了SPH030或之后补丁，则检查通过；
        if Products.compareVersion(self.product_hotpatch,
                                   PATCH_KEY_FOR_26_V_VER_DICT.get(
                                           self.product_version)) >= 0:
            return True, "", "", config.PatchKey.NO_NAS

        # 3、查询是否安装NAS补丁。
        patch_key, err_key, cli_ret = self.check_install_nas_patch()
        log.info(self.data_dict,
                 "By installed NAS Patch The patch key is:%s and err_key is:%s"
                 % (patch_key, err_key))
        if not patch_key:
            return False, err_key, cli_ret, patch_key
        return True, "", "", patch_key

    def get_patch_key_by_version(self):
        """
        根据版本号获取补丁包关键字
        V300R006C20之前的版本选择NoNAS包；V300R006C60之后选择NAS补丁包；
        V300R006C20及之后且V300R006C60之前的，当前设备没有补丁，选择NAS补丁包；
        :return:
        """
        if self.product_version < PATCH_KEY_FOR_26_V_VER_RANGE[0]:
            return config.PatchKey.NO_NAS
        if self.product_version >= PATCH_KEY_FOR_26_V_VER_RANGE[1]:
            return config.PatchKey.NAS

        log.info(self.data_dict,
                 "current hot patch version:%s" % self.product_hotpatch)
        if not self.product_hotpatch or self.product_hotpatch == "--":
            return config.PatchKey.NAS

        return ""

    def get_patch_key_by_file_system(self):
        """
        根据是否存在文件系统获取补丁包关键字；如果存在文件系统，提示联系技术支持工程师；
        如果没有文件系统，选择NoNAS补丁包（前提条件当前设备已经安装有补丁）
        :return: patch_key,err_key,cli_ret
                patch_key:NAS/NoNAS/"";
        """
        flag, file_sys_list, cli_ret = cliUtil.get_file_system_info(self.cli,
                                                                    self.lang)
        if not flag:
            err_key = "FSConfigCheck.notpass.get.filesys.error"
            return "", err_key, cli_ret
        # 如果存在文件系统，检查不通过
        if file_sys_list:
            log.info(self.data_dict, "exist file system or license.")
            err_key = "FSConfigCheck.notpass.exist.filesys"
            return "", err_key, cli_ret
        return config.PatchKey.NO_NAS, "", cli_ret

    def check_install_nas_patch(self):
        # 如果查到有补丁且安装的是NO-NAS的补丁则报错（小系统ls -l /OSM/coffer_bin/hotpatch/patch_cur
        # 查看是否有cmr_auth_、cmr_store_、cmr_cm_、cmr_kagent、ndmp_其中的一个，
        # 如果有则是NAS补丁，否则为NO-NAS的补丁）

        log.info(self.data_dict,
                 "get is_install_nas_patch start.")
        keylist = ["cmr_auth_", "cmr_store_", "cmr_cm_", "cmr_kagent", "ndmp_"]
        cmd = "ls -l /OSM/coffer_bin/hotpatch/patch_cur"
        flag, cli_ret, errMsg = cliUtils.excuteCmdInMinisystemModel(self.cli,
                                                                    cmd,
                                                                    self.lang)
        if flag is not True:
            log.info(self.data_dict,
                     "get is_install_nas_patch failed.")
            err_key = "FSConfigCheck.get.install.nas.error"
            return "", cli_ret, err_key

        for key in keylist:
            if key in cli_ret:
                return config.PatchKey.NAS, cli_ret, ""
        return config.PatchKey.NO_NAS, cli_ret, ""
