#!/bin/bash

# This script runs every Friday night to truncate all Docker container logs.
# NOTE: To clean raw Docker container logs (e.g., /var/lib/docker/containers/*/*.log)
# from inside the cron container, the cron container MUST have access to the host's
# Docker socket or the /var/lib/docker/containers volume.

echo "$(date): Attempting to clean Docker container logs..."

# If docker is available, try to fetch paths and truncate (requires socket mount)
if command -v docker &> /dev/null; then
    for container in $(docker ps -q); do
        logpath=$(docker inspect --format='{{.LogPath}}' "$container" 2>/dev/null)
        if [ -n "$logpath" ] && [ -f "$logpath" ]; then
            echo "Truncating logs for container $container..."
            truncate -s 0 "$logpath"
        fi
    done
else
    # Fallback to direct path truncation if /var/lib/docker is mounted into the cron container
    echo "Docker command not found inside container. Attempting direct file truncation..."
    if [ -d "/var/lib/docker/containers" ]; then
        find /var/lib/docker/containers -name "*-json.log" -type f -exec truncate -s 0 {} \;
        echo "Truncated files in /var/lib/docker/containers."
    else
        echo "ERROR: Cannot clean host docker logs from inside this container."
        echo "Please mount /var/run/docker.sock OR /var/lib/docker/containers to the cron_worker container in docker-compose.yml."
    fi
fi

echo "$(date): Docker log clean-up check complete."
