#!/usr/bin/env python3

"""
实例单实例架构下的 MySQL 安装与卸载
"""

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

from dbma.backup import (MySQLDumpFullBackup, MySQLDumpNoDataBackup,    # mysqldump 备份
                         MySQLBackupFullBackup, MySQLBackupDiffBackup,  # mysqlbackup 备份
                         usable_backup_tools)


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('--user', type=str, default='root', help="backup user")
    parser.add_argument('--password', type=str,
                        default="dbma@0352", help="backup user")
    parser.add_argument('--log', type=str, default='info',
                        choices=['debug', 'info', 'warning', 'error'])
    parser.add_argument('action', type=str, choices=[
                        'full-backup', 'diff-backup', 'only-schema'])
    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()

    # 查询出所有可用的备份工具
    tools = usable_backup_tools(
        host=args.host, port=args.port, user=args.user, password=args.password)

    if len(tools) == 0:
        logger.error("there are not usable backup tool exists! backup fail.")
        return

    logger.info(f"prepare execute {args.action} backup")

    if args.action == 'only-schema':

        # only-schema 备份
        if 'mysqldump' not in tools:

            # 由于 mysqldump 不存在所以备份不了
            logger.error("mysqldump not exists backup schema fail !")
        else:
            dump = MySQLDumpNoDataBackup(
                host=args.host, port=args.port, user=args.user, password=args.password)
            dump.backup()

    elif args.action == 'full-backup':

        # 全量备份
        first, *_ = tools
        if first == 'mysqlbackup':

            # mysqlbackup 全量
            dump = MySQLBackupFullBackup(
                host=args.host, port=args.port, user=args.user, password=args.password)
            dump.backup()
        else:

            # mysqldump 作为一个保底工具
            if 'mysqldump' not in tools:
                logger.error(
                    "There are no backup tools available in current computer.")
                return

            # mysqldump 全量
            dump = MySQLDumpFullBackup(
                host=args.host, port=args.port, user=args.user, password=args.password)
            dump.backup()
    elif args.action == 'diff-backup':

        # 差异备份
        if 'mysqlbackup' in tools:

            # 使用 mysqlbackup 进行差异备份
            dump = MySQLBackupDiffBackup(
                host=args.host, port=args.port, user=args.user, password=args.password)
            dump.backup()

            return

        # 如果可以执行到这里说明主机上不存在 mysqlbackup
        logger.error(
            f"There are no backup tools available in current computer.")
        return


if __name__ == "__main__":
    main()
