# -*- coding: utf-8 -*-
import pathlib
import re
import time
import traceback
import utils.common.log as logger
from utils.common.ssh_util import Ssh
from plugins.DistributedStorage.scripts.logic.InstallOperate import InstallOperate
from plugins.DistributedStorage.scripts.utils.common.DeployConstant import DeployConstant


class ConfigureRaidModeImpl:
    def __init__(self, fs_args):
        self.error_msg = {}
        self.bmc_info_list = fs_args.get("bmc_info_list")

    def procedure(self):
        logger.info("Start to config raid tool")
        for bmc_info in self.bmc_info_list:
            status, details = ConfigRaidTool(bmc_info).run()
            if not status:
                self.error_msg[bmc_info.get("manageIp")] = details
        if self.error_msg:
            raise Exception(self.error_msg)
        logger.info("The configuration is complete")


class ConfigRaidTool:
    """安装配置RAID卡工具"""

    TYPE_CHECK_MAP = {
        "config_3152_arcconf_handle": (DeployConstant.DRIVER_TYPE_CONDITION.get("3152").get("cmd"),
                                       DeployConstant.DRIVER_TYPE_CONDITION.get("3152").get("pattern"))
    }

    def __init__(self, node_info: dict):
        self.om_ip = node_info.get("manageIp")
        _, self.root_pwd, self.user, self.user_passwd = node_info["creuser"].split(',')
        self.ssh_client = InstallOperate.create_ssh_root_client(self.om_ip, self.user, self.user_passwd, self.root_pwd)

    def run(self):
        try:
            getattr(self, self.get_handle())()
        except Exception as e:
            logger.error("Error:{}, details:{}".format(e, traceback.format_exc()))
            return False, str(e)
        finally:
            Ssh.ssh_close(self.ssh_client)
        return True, ""

    def get_handle(self):
        """校验是否由插件配置RAID卡工具"""
        for _handle, (check_cmd, check_pattern) in self.TYPE_CHECK_MAP.items():
            ret = Ssh.ssh_exec_command_return(self.ssh_client, check_cmd)
            if re.search(check_pattern, str(ret)):
                logger.info("Node:{}, config raid handle:{}, cmd result:{}".format(self.om_ip, _handle, ret))
                return _handle
        return "default_handle"

    def default_handle(self):
        logger.info("[]The RAID tool does not need to be configured".format(self.om_ip))
        return

    def config_3152_arcconf_handle(self):
        """安装BP3152RIAD工具"""
        tool_name = "Arcconf-4.09-25611.aarch64.rpm"
        self.upload_tool(src=str(DeployConstant.TOOL_PATH).format(tool_name))
        cmd = "rpm -qa | grep -v grep| grep Arcconf-4.09-25611;" \
              "if [ $? -eq 0 ];" \
              "then echo 'The Arcconf exists'; " \
              "else " \
              "rpm -Uvh /tmp/%s;" \
              "fi && whoami" % tool_name
        try:
            self.install_tool(cmd)
        finally:
            self.clear_tool(tool_name)
        self.re_scanning_disk()

    def re_scanning_disk(self):
        stop_cmd = "SMIO_DIR=$(ls -l /proc/`pidof smio_jbodmng` | grep smio_jbodmng | awk '{print $11}' | " \
                   "xargs dirname);cd $SMIO_DIR;sh smio_stop"
        start_cmd = "SMIO_DIR=$(ls -l /proc/`pidof smio_jbodmng` | grep smio_jbodmng | awk '{print $11}' | " \
                    "xargs dirname);cd $SMIO_DIR;sh smio_start"
        Ssh.ssh_send_command(self.ssh_client, stop_cmd, expect="done", timeout=60)
        logger.info("[{}]Succeeded in stopping the SMIO".format(self.om_ip))
        time.sleep(10)
        Ssh.ssh_send_command(self.ssh_client, start_cmd, expect="done", timeout=60)
        logger.info("[{}]SMIO started successfully".format(self.om_ip))

    def upload_tool(self, src: str, dst: str = "/tmp"):
        cmd = "[ -e {0} ] && rm -f {0} && whoami".format(pathlib.Path(dst, pathlib.Path(src).name))
        Ssh.ssh_send_command(self.ssh_client, cmd, expect="root", timeout=10)
        Ssh.put_file(self.om_ip, self.user, self.user_passwd, src, dst)
        logger.info('copy {} to node[{}] success'.format(src, self.om_ip))

    def install_tool(self, cmd, expect="root"):
        ret = Ssh.ssh_exec_command_return(self.ssh_client, cmd, timeout=20)
        if str(ret).__contains__(expect):
            return
        logger.error("install tool failed, details:{}".format(ret))
        raise Exception(ret)

    def clear_tool(self, tool_name, dst: str = "/tmp"):
        cmd = "[ -e {0} ] && rm -f {0} && whoami".format(pathlib.Path(dst, tool_name))
        Ssh.ssh_send_command(self.ssh_client, cmd, expect="root", timeout=10)
        logger.info("Tool package {} deleted successfully".format(tool_name))
