#!/usr/bin/env python3
'''
Delete all but the last # core dumps from config.
'''

import os
import sys
import yaml
import logging

CONFIG = "/etc/remove_old_coredumps.conf"
LOG = "/var/log/remove_old_coredumps.log"

LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.INFO)
HANDLER = logging.FileHandler(LOG)
HANDLER.setLevel(logging.INFO)
FORMATTER = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
HANDLER.setFormatter(FORMATTER)
LOGGER.addHandler(HANDLER)

try:
    with open(CONFIG, 'r') as config:
        DOC = yaml.load(config)
        DIR = DOC["config"]["directory"]
        KEEP = DOC["config"]["keep"]
        LOGGER.info("Imported config: {}. Dir: {}. " \
                "Keep files: {}".format(CONFIG, DIR, KEEP))
except Exception:
    LOGGER.info("Can't import config: " + CONFIG)
    sys.exit()

def delete_old_files(path, keep):
    '''
    Recursively delete old file in a given dir.
    '''
    files_list = []
    for content in os.listdir(path):
        content = path + "/" + content
        if os.path.isfile(content) and content.endswith(('hprof.gz', 'hprof.zst')):
            files_list.append(content)
        elif os.path.isdir(content):
            delete_old_files(content, keep)
    files_list.sort()
    for file in files_list[:-keep]:
        name = file[len(DIR) + 1:]
        LOGGER.info("Deleting: " + name)
        #print(file)
        os.remove(file)

delete_old_files(DIR, KEEP)
