# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
from utils.common.fic_base import TestCase
import utils.common.log as logger
from utils.common.ssh_util import Ssh as ssh
from plugins.DistributedStorage.scripts.logic.vm_operate import VMOperate


class ConfigFirstLogin(TestCase):
    def __init__(self, project_id, pod_id, fs_args_list):
        super(ConfigFirstLogin, self).__init__(project_id, pod_id)
        self.fs_args_list = fs_args_list

    @staticmethod
    def config_fsm_vm_first_login(vm_info):
        host_ip = vm_info.get("om_ip")
        user = vm_info.get("user")
        user_pwd = vm_info.get("passwd")
        root_pwd = vm_info.get("root_pwd")
        logger.info("Host [%s] first login set start!" % host_ip)
        try:
            ssh_client = ssh.ssh_create_client(host_ip, user, user_pwd)
        except Exception as e:
            if str(e).find("password has expired, please modify password") != -1:
                logger.info("Host [%s] first login set success!" % host_ip)
                return
            raise Exception from e
        cmd_res = ssh.ssh_send_command(ssh_client, 'su -', 'assword:', 20)
        logger.info("exe cmd[su root] result:%s" % (str(cmd_res)))
        cmd_res = ssh.ssh_send_command(ssh_client, root_pwd, '#', 20)
        logger.info("exe cmd[#] result:%s" % (str(cmd_res)))
        cmd_res = ssh.ssh_send_command(ssh_client, 'TMOUT=0', '#', 20)
        logger.info("exe cmd[TMOUT=0] result:%s" % (str(cmd_res)))
        # 密码默认有效期90天，设置用户上次登录时间为89天前，预留一天时间确认安装部署工程完成后再生效
        cmd = "chage -d `date -d \"89 day ago\" +%Y-%m-%d` fsadmin;" \
              "chage -d `date -d \"89 day ago\" +%Y-%m-%d` root;"
        ssh.ssh_send_command(ssh_client, cmd, '#', 20)
        logger.info("Host [%s] first login set success!" % host_ip)

    def procedure(self):
        logger.info('Start to configure fsm first login.')
        for fs_args in self.fs_args_list:
            float_ip = fs_args.get('float_ip')
            if not float_ip:
                continue
            vm_operate = VMOperate(self.project_id, self.pod_id, fs_args)
            master_fsm, standby_fsm = vm_operate.get_vm_data(self.pod_id, fs_args.get('float_ip'))
            self.config_fsm_vm_first_login(master_fsm)
            self.config_fsm_vm_first_login(standby_fsm)
