#!/usr/bin/env python3

import os
import re
import sys
import stat
import logging
import argparse
from datetime import datetime
from datetime import timedelta

name = os.path.basename(__file__)
logging.basicConfig(format="%(asctime)s %(levelname)s %(message)s",level=logging.INFO)

def parser_cmd_args() -> argparse.ArgumentParser:
    """
    处理命令行参数
    """
    def str_to_bool(s):
        if s.upper() in ('YES','TRUE','ON'):
            return True
        else:
            return False
    
    parser = argparse.ArgumentParser(name)
    parser.add_argument('--black-list-mode',default='ON',type=str_to_bool,help='backup mode default on')
    parser.add_argument('--not-used-days',type=int,default=30,help="how long the table not used(days)")
    parser.add_argument('datadir',type=str,default="/database/mysql/data/3306/",help="mysql datadir")
    args = parser.parse_args()
    return args


def main():
    """
    解析出若干天之内都没有访问过的表
    """
    args = parser_cmd_args()
    baseline = datetime.now() - timedelta(days=args.not_used_days)
    datadir = args.datadir

    logging.info(f"分析数据目录({datadir})")
    if args.black_list_mode:
        logging.info(f"准备过虑出最近修改日期(mtime) < {baseline.isoformat()}")
    else:
        logging.info(f"准备过虑出最近修改日期(mtime) > {baseline.isoformat()}")
    
    if not os.path.isdir(datadir):
        logging.error(f"dir '{datadir}' not exits or permission denied ")
        exit(1)

    # 广度优先搜索 datadir

    schemas = []

    # 解析出存在的数据库
    for item in os.listdir(args.datadir):
        path = os.path.join(datadir,item)
        if os.path.isdir(path):
            schemas.append(item)
    schemas = [schema for schema in schemas if schema not in ('mysql','information_schema','sys','performance_schema')]

    expired_tables = []
    # 从数据库的目录解析文件
    for schema in schemas:
        for item in os.listdir(os.path.join(datadir,schema)):
            path = os.path.join(datadir,schema,item)
            if os.path.isfile(path) and ( path.endswith('.ibd') or path.endswith('.MYD') ):
                # 是 .ibd 文件或 .MYD 文件
                *_,atime,mtime,ctime = os.stat(path)
                mtime = datetime.fromtimestamp(mtime)
                if mtime < baseline and args.black_list_mode:
                    table,*_ = item.split('.')
                    expired_tables.append(f"{schema}.{table}")
                elif args.black_list_mode == False and mtime > baseline:
                    table,*_ = item.split('.')
                    expired_tables.append(f"{schema}.{table}")

    for table in expired_tables:
        print(table)


if __name__ == "__main__":
    main()