#!/usr/bin/env python3

from pathlib import Path
import time

# Cache locations to clean.
# Add/remove paths here as needed.
CACHE_DIRS = [
    Path("/srv/iptv/cache"),
    Path("/srv/iptv/tmp"),
]

# Remove files older than this many days.
MAX_AGE_DAYS = 14
cutoff = time.time() - (MAX_AGE_DAYS * 86400)

removed_files = 0
removed_dirs = 0

for cache_dir in CACHE_DIRS:
    if not cache_dir.is_dir():
        continue

    # Delete old regular files only.
    for path in cache_dir.rglob("*"):
        try:
            if path.is_file() and not path.is_symlink():
                if path.stat().st_mtime < cutoff:
                    path.unlink()
                    removed_files += 1
        except (FileNotFoundError, PermissionError) as exc:
            print(f"Skipping {path}: {exc}")

    # Remove empty directories, deepest first.
    directories = sorted(
        (p for p in cache_dir.rglob("*") if p.is_dir()),
        key=lambda p: len(p.parts),
        reverse=True,
    )

    for path in directories:
        try:
            path.rmdir()
            removed_dirs += 1
        except OSError:
            pass

print(
    f"IPTV cache cleanup complete: "
    f"{removed_files} files removed, {removed_dirs} empty directories removed"
)
