#!/usr/bin/env python3

# Usage:
#    python3 aldpro-ccache-sweeper.py
#    python3 aldpro-ccache-sweeper.py path [path2 [path3]]
#    python3 aldpro-ccache-sweeper.py /run/ipa/ccaches/ /run/ipa/ccaches/*/

import os
import sys
import time

DEFAULT_CCACHES_DIR_PATH = '/run/ipa/ccaches/'
CCACHES_LIFE_TIME = 24 * 60 * 60 # sec
TIME_NOW = time.time()

def is_old(path):
    mtime = os.path.getmtime(path)
    return TIME_NOW - mtime > CCACHES_LIFE_TIME

def sweep(dir_path):
    for path in os.listdir(dir_path):
        path = os.path.join(dir_path, path)
        if os.path.isfile(path) and is_old(path):
            os.unlink(path)

if __name__ == "__main__":
    if len(sys.argv) > 1:
        for dir_path in sys.argv[1:]:
            if not os.path.isdir(dir_path):
                raise Exception(f'Directory "{dir_path}" does not exists. Exiting')
        for dir_path in sys.argv[1:]:
            sweep(dir_path)
    else:
        sweep(DEFAULT_CCACHES_DIR_PATH)