# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
import pathlib
import traceback

import utils.common.log as logger
from utils.common.ssh_util import Ssh
from utils.common.message import Message
from utils.common.exception import HCCIException
from utils.common.fic_base import StepBaseInterface
from utils.DBAdapter.DBConnector import BaseOps
from utils.business.project_condition_utils import get_project_condition_boolean
from plugins.DistributedStorage.logic.vm_operate import VMOperate
from plugins.DistributedStorage.logic.install_operate import InstallOperate
from plugins.DistributedStorage.utils.iterm.parameter_gain import ParamsGain


class UploadOEMPkgIntf(StepBaseInterface):
    def __init__(self, project_id, pod_id):
        super(UploadOEMPkgIntf, self).__init__(project_id, pod_id)
        self.project_id = project_id
        self.pod_id = pod_id
        self.base_ops = BaseOps()
        self.params = ParamsGain(project_id, pod_id, self.base_ops)
        if get_project_condition_boolean(self.project_id, 'TenantStorFB80&ExpansionServiceStorage'):
            self.fs_args = self.params.get_business_separate_expand_fusionstorage_args()
        else:
            self.fs_args = self.params.get_business_separate_args()
        self.oem_error_code = 626397
        self.oem_pkg = "oem.tgz"

    def execute(self, project_id, pod_id):
        """
        标准调用接口：重试
        :param project_id:
        :param pod_id:
        :return:
        """
        try:
            self.procedure()
        except HCCIException as err:
            logger.error("Upload OEM package Error:{}, details:{}".format(err, traceback.format_exc()))
            return Message(500, err)
        except Exception as err:
            logger.error("Upload OEM package Error:{}, details:{}".format(err, traceback.format_exc()))
            return Message(500, err)
        return Message()

    def rollback(self, project_id, pod_id):
        """
        标准调用接口：执行回滚
        :param project_id:
        :param pod_id:
        :return:Message类对象
        """
        return Message()

    def retry(self, project_id, pod_id):
        """
        标准调用接口：重试
        :return: Message类对象
        """
        return self.execute(self.project_id, self.pod_id)

    def procedure(self):
        product_pkg_path = pathlib.Path(self.params.get_pkg_path('fs'))
        if not product_pkg_path.name.startswith("Distributed-Storage"):
            logger.info("Product pkg name:{}, no need OEM pkg, pass".format(product_pkg_path))
            return

        pkg_path, oem_pkg_name = self.params.get_package(f"^{self.oem_pkg}$")
        logger.info("package path:{}, package name:{}".format(pkg_path, oem_pkg_name))
        if not oem_pkg_name:
            logger.error("The {} package does not exist in the {} directory.".format(self.oem_pkg, pkg_path))
            raise HCCIException(self.oem_error_code, self.oem_pkg, pkg_path)

        vm_opr = VMOperate(self.project_id, self.pod_id, self.fs_args)
        vm_data_list = vm_opr.get_vm_data(self.pod_id, self.fs_args.get("float_ip"))
        for info in vm_data_list:
            self.upload_oem_pkg(info, pkg_path)

        logger.info("The oem package has been uploaded.")

    def upload_oem_pkg(self, vm_info, pkg_path):
        src = str(pathlib.Path(pkg_path) / self.oem_pkg)
        dst_dir = str(pathlib.Path("/home") / vm_info.get('user'))
        Ssh.put_file(vm_info.get('om_ip'), vm_info.get('user'), vm_info.get('passwd'), src, destination=dst_dir)
        logger.info("The oem package {} is uploaded successfully.".format(self.oem_pkg))

        ssh_client = InstallOperate.create_ssh_root_client(
            vm_info.get('om_ip'), vm_info.get('user'), vm_info.get('passwd'), vm_info.get("root_pwd")
        )

        dfv_dir = "/opt/dfv"
        oem_dir = "/opt/dfv/oem"
        cmd_items = [f'test -d {dfv_dir} && rm -rf {oem_dir}',
                     f'mkdir -p {oem_dir}',
                     f'chmod -R 755 {dfv_dir}',
                     f'chown -hR root:root {dfv_dir}']
        cmd_dir = ";".join(cmd_items)
        Ssh.ssh_send_command(ssh_client, cmd_dir, "#", 30, 3)
        logger.info("The oem directory {} is created successfully.".format(oem_dir))

        cmd_items = [f"tar -zxf {dst_dir}/{self.oem_pkg} -C {oem_dir}",
                     f"find {oem_dir} -type d -print | xargs chmod 755",
                     f"find {oem_dir} -type f -print | xargs chmod 644",
                     f"chown -hR root:root {oem_dir}",
                     f"find {oem_dir} -type f -print | xargs dos2unix",
                     f"rm -rf {dst_dir}/{self.oem_pkg}"]
        cmd_dir = ";".join(cmd_items)
        Ssh.ssh_send_command(ssh_client, cmd_dir, "#", 30, 3)
        logger.info("The oem package is decompressed successfully.")
