# -*- coding: UTF-8 -*-
"""
@desc: 启动电源补丁升级
@date: 2023.01.09
"""
import time

from com.huawei.ism.tool.obase.utils import ManualConfigItemMgr
from cbb.frame.cli import cliUtil
from cbb.frame.context import contextUtil
from cbb.frame.base import baseUtil
from cbb.frame.base.exception import UnCheckException
from common.baseFactory import log

# 启动电源升级的开关
STOP_POWER_BACKEND_UPGRADE_ENABLE = "power.backend.upgrade.enable"

RETRY_TIMES = 5
# 重试的时间间隔为5秒
RETRY_INTERVAL = 5


def execute(context):
    lang = context.get('lang')
    return stop_power_backend_upgrade(context, lang)


def stop_power_backend_upgrade(data_dict, lang):
    """
    停止电源补丁的后台升级。

    :return: 是否成功关闭，报错信息，回显。
    """
    cli = contextUtil.getCli(data_dict)
    # ignoreItem.txt中,电源升级的开关。
    if ManualConfigItemMgr.getInstance().expected(STOP_POWER_BACKEND_UPGRADE_ENABLE, "yes"):
        log.info(data_dict, "need to start psu upgrade.")
        return True, "", ""

    try:
        # 判断是否为0节点。
        current_ctrl_id = cliUtil.get_current_ctrl_id(cli, lang)
        if current_ctrl_id == "0":
            return stop_power_upgrade(cli, lang)
        # 跳转到0节点
        return ssh_to_0_node_stop_power_backend_upgrade(cli, data_dict, lang)
    except Exception as ex:
        log.error(data_dict, "exception:{}".format(ex))
        return False, baseUtil.getPyResource(lang, "stop.power.upgrade.fail"), ""
    finally:
        # 回退到cliMode。
        cliUtil.enterCliModeFromSomeModel(cli, lang)


def ssh_to_0_node_stop_power_backend_upgrade(cli, data_dict, lang):
    """
    跳转到0节点执行停止电源升级。
    """
    try:
        password = data_dict.get('dev').getLoginUser().getPassword()
        ssh_to_0_node(cli, data_dict, lang, password)
        # 执行启动电源补丁升级的命令。
        return stop_power_upgrade(cli, lang)
    except Exception as ex:
        log.error(data_dict, "exception:{}".format(ex))
        return False, baseUtil.getPyResource(lang, "stop.power.upgrade.fail"), ""
    finally:
        # 删除本地密码
        del password
        cliUtil.exit_heart_beat_mini_sys(cli, True, lang)


def ssh_to_0_node(cli, data_dict, lang, password):
    for count in range(RETRY_TIMES):
        log.info(data_dict, "ssh to 0 node time:{}".format(count))
        cmd = "sshtoremoteExt {}".format(0)
        is_success, ssh_cli_ret, err_msg = cliUtil.ssh_remote_ctrl_even_mini_sys(cli, cmd, password, lang)
        if is_success:
            log.info(data_dict, "Ssh to 0 controller successful.")
            return
        # 重试的时间间隔为5秒
        time.sleep(RETRY_INTERVAL)
    raise UnCheckException("ssh to 0 node failed.")


def stop_power_upgrade(cli, lang):
    """
    执行停止电源补丁升级的命令。eam.sh psu_upgrade_permit off
    命令执行失败不支持返回True
    如果为operation success则返回True,否则False
    """
    upgrade_power_patch_cmd = "eam.sh psu_upgrade_permit off"
    flag, cli_ret, err_msg = cliUtil.excuteCmdInMinisystemModel(cli, upgrade_power_patch_cmd, lang)
    if flag is not True:
        return True, "", ""
    if "operation success" in cli_ret:
        return True, "", ""
    if "operation fail." in cli_ret:
        return False, baseUtil.getPyResource(lang, "stop.power.upgrade.fail"), ""
    return True, "", ""
