#!/usr/bin/env python3

"""
实例 clone 
"""

import os
import sys
import psutil
import logging
import argparse
import shutil
from dbma import common
from dbma import checkings
from dbma.mysqldeploy import MySQLCloner


def parser_cmd_args():
    """
    实现命令行参数的处理
    """
    name, *_ = os.path.basename(__file__).split('.')
    parser = argparse.ArgumentParser(name)
    parser.add_argument('--port', type=int, default=3306, help="instance port")
    parser.add_argument('--host', type=str,
                        default="127.0.0.1", help="host ip")
    parser.add_argument('--clone-password', type=str,
                        default="dbma@0352", help="backup user")
    parser.add_argument('--pkg', type=str, default="mysql-8.0.18-linux-glibc2.12-x86_64.tar.xz",
                        help="mysql install package")
    parser.add_argument('--log', type=str, default='info',
                        choices=['debug', 'info', 'warning', 'error'])
    parser.add_argument('action', type=str, choices=[
                        'local-clone', 'remote-clone'])
    args = parser.parse_args()
    return args


def main():
    """
    完成备份相关的功能
    """
    # 配置日志
    args = parser_cmd_args()
    level = getattr(logging, args.log.upper())
    logger = logging.getLogger('dbm-agent')
    logger.setLevel(level)
    stream_handler = logging.StreamHandler()
    stream_handler.setLevel(logging.DEBUG)
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(threadName)s - %(levelname)s - %(lineno)s  - %(message)s')
    stream_handler.setFormatter(formatter)
    logger.addHandler(stream_handler)

    args = parser_cmd_args()
    cores = psutil.cpu_count()

    if args.action == 'local-clone':

        # 本地克隆
        logger.info("enter local clone logic")

        # 创建用于备份的任务线程
        cloner = MySQLCloner(host='127.0.0.1', port=args.port, clone_user="cloneuser",
                             clone_password=args.clone_password, cores=cores)
        cloner.start()
        cloner.join()

    elif args.action == 'remote-clone':

        # 克隆远程实例到本地
        logger.info("enter remonte clone logic")
        cloner = MySQLCloner(host=args.host, port=args.port, clone_user="cloneuser",
                             clone_password=args.clone_password, cores=cores)
        cloner.start()
        cloner.join()
    else:

        # 不支持的操作
        logger.error("not supported operation")


if __name__ == "__main__":
    main()
