#!/usr/bin/python3
# pylint: disable=invalid-name
# pylint: disable=consider-using-f-string
# pylint: disable=fixme
# pylint: disable=line-too-long
"""
 SAPHanaSR-cibBrush
 Author:       Fabian Herschel, June 2023
 License:      GNU General Public License (GPL)
 Copyright:    (c) 2023-2026 SUSE LLC

 Allows to reduce pengine files based on timestamps (--before YYYY-M-D H:M:S,
 --after YYYY-M-D H:M:S)
 This should normaly only doen on a copy of the pengine files (like a crm_report archive)

"""

# pylint: enable=invalid-name
#global TOOL_VERSION
TOOL_VERSION = "1.0.20260202"

# pylint: disable=wrong-import-position
# pylint: disable=unused-import
import argparse
import json
import os
import re
import sys
from dateutil import parser as dateutil_parser
sys.path.insert(1, '/usr/lib/SAPHanaSR-angi')
from saphana_sr_tools import HanaCluster,HanaStatus
# pylint: enable=wrong-import-position
# pylint: enable=unused-import

if __name__ == "__main__":
    my_cluster = HanaCluster()
    parser = argparse.ArgumentParser()
    parser.add_argument("--dir", nargs="+", help="specify the directory where to search for cib files (alternative for --cib)")
    parser.add_argument("--before", help="BRUSH: select 'before' - timepoint ('YYYY-M-D H:M:S')")
    parser.add_argument("--after", help="BRUSH: select 'to' - timepoint ('YYYY-M-D H:M:S')")
    parser.add_argument("--list", help="BRUSH: list cib times and exit", action="store_true")
    parser.add_argument("--version", help="output version and exit", action="store_true")
    args = parser.parse_args()
    if args.version:
        print(f"{TOOL_VERSION}")
        sys.exit(0)
    if args.dir:
        my_cluster.config['dir_list'] = args.dir
    list_only = args.list
    if 'before' in vars(args) and vars(args)['before']:
        dt = dateutil_parser.parse(vars(args)['before'])
        my_cluster.config['before'] = int(dt.timestamp())
    if args.after:
        dt = dateutil_parser.parse(args.after)
        my_cluster.config['after'] = int(dt.timestamp())
    dir_list = my_cluster.config.get('dir_list', None)
    cib_file_list = my_cluster.config.get('cib_file_list', [])
    if dir_list:
        for single_dir in dir_list:
            file_list = my_cluster.find(single_dir, pattern=my_cluster.config.get('pattern_list', None)) # use default patterns pe-input-nnn.bz2 and pe-warn-nnn.bz2
            if file_list:
                cib_file_list.extend(file_list)
    #
    # here the cib files iteration would begin
    #   - we need to read all given cib files
    #   - either list all (list_only)
    #   - or select some for deletion by timestamp (before, after)
    #
    for cib_file in cib_file_list:
        my_hana    = HanaStatus(my_cluster.config, selections=my_cluster.selections)
        my_hana.xml_import(cib_file)
        my_hana.fill_glob_dict()
        if 'cib-time' in my_hana.glob_dict['global']:
            dt = dateutil_parser.parse(my_hana.glob_dict['global']['cib-time'])
            cibtime = int(dt.timestamp())
            if list_only:
                print(f"{cib_file} ({dt})")
            else:
                #
                # check, if file should be deleted (selected by timestamp)
                #
                my_hana.ts = cibtime
                before_ts = my_cluster.config.get('before',None)
                after_ts = my_cluster.config.get('after',None)
                if before_ts and cibtime < before_ts:
                    print(f"rm {cib_file} # before ({dt})")
                elif after_ts and cibtime > after_ts:
                    print(f"rm {cib_file} # after  ({dt})")
                else:
                    continue

    if len(cib_file_list) == 0:
        print("ERROR: No cib files found")
        sys.exit(2)
