#!/bin/bash

DIR="/var/log/VeeamBackup"
THRESHOLD=90

get_usage() {
    df -P "$DIR" | awk 'NR==2 { sub(/%/, "", $5); print $5 }'
}

USAGE=$(get_usage)
if (( USAGE < THRESHOLD )); then
    exit 0
fi

echo "Disk usage is ${USAGE}%, starting cleanup..."

mapfile -t FILES < <(
    find "$DIR" -type f \( -name '*.log.gz' -o -name '*.zip' \) -print0 |
    while IFS= read -r -d '' file; do
        # %W = birth time (epoch), -1 if unsupported
        btime=$(stat -c '%W' "$file" 2>/dev/null || echo -1)
        if [[ "$btime" -gt 0 ]]; then
            echo "$btime|$file"
        fi
    done |
    sort -n |
    cut -d'|' -f2-
)

if (( ${#FILES[@]} == 0 )); then
    echo "No deletable files found (or filesystem does not support creation time)."
    exit 0
fi

DELETED=false

for file in "${FILES[@]}"; do
    USAGE=$(get_usage)

    if (( USAGE < THRESHOLD )); then
        echo "Disk usage reduced to ${USAGE}%, stopping cleanup."
        break
    fi

    echo "Deleting $file"
    rm -vf "$file"
    DELETED=true
done

if $DELETED; then
    echo "Cleanup finished. Final disk usage: $(get_usage)%"
else
    echo "No files deleted. Disk usage still ${USAGE}%"
fi