#!/usr/bin/python3
# Clean testbench logs directory to only keep unique and useful files

import hashlib
from pathlib import Path
from string import whitespace

DIR = Path("test")


def rmtree(p: Path):
    """Recursively delete file or directory"""
    if p.exists():
        if p.is_dir():
            for child in p.iterdir():
                rmtree(child)
            p.rmdir()
        else:
            p.unlink()


def remove(p: Path, reason: str):
    """Announce and recursively remove file or directory"""
    print(f"rm {reason} {p}")
    rmtree(p)


content_hashes = set()


def rm_if_similar(p: Path, content: str):
    """Delete file if another file has the same content"""
    # Remove whitespace from file
    normalized = content.translate(str.maketrans("", "", whitespace))
    # Hash their content
    hash = hashlib.blake2b(normalized.encode(), usedforsecurity=False).hexdigest()
    if hash in content_hashes:
        remove(p, "similar")
    else:
        content_hashes.add(hash)


for platform in DIR.iterdir():
    if not platform.is_dir():
        continue
    for date in platform.iterdir():
        if not date.is_dir():
            continue
        for request in date.iterdir():
            payload_file_path = request.joinpath("payload.xml")
            payload_dir_path = request.joinpath("payload")

            if payload_file_path.exists():
                content = payload_file_path.read_text()
                if "HAC" in request.name and "ORDER_HAC_FINAL_NEG" not in content:
                    remove(request, "simple hac")
                elif "HAA" in request.name and "<Service>" not in content:
                    remove(request, "empty haa")
                elif "wssparam" in request.name:
                    remove(request, "wssparam")
                else:
                    rm_if_similar(payload_file_path, content)
            elif payload_dir_path.exists():
                for file in payload_dir_path.iterdir():
                    content = file.read_text()
                    rm_if_similar(file, content)
                if not any(payload_dir_path.iterdir()):
                    remove(request, "empty request")
            elif (
                request.name != "fetch"
                and request.name != "submit"
                and not payload_file_path.exists()
                and not payload_dir_path.exists()
            ):
                remove(request, "empty request")

        if not any(date.iterdir()):
            remove(date, "empty dir")
