#!/bin/bash
# Removes unused Docker images, stopped containers, and dangling volumes.
# Runs every 2 hours via cron — see scripts/cronjobs.md for setup.

LOG_FILE="/tmp/docker-cleanup.log"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')

echo "[$TIMESTAMP] Starting Docker cleanup..." >> "$LOG_FILE"

# Remove stopped containers
CONTAINERS=$(docker container prune -f 2>&1)
echo "[$TIMESTAMP] Containers: $CONTAINERS" >> "$LOG_FILE"

# Remove dangling images (untagged layers with no container)
DANGLING=$(docker image prune -f 2>&1)
echo "[$TIMESTAMP] Dangling images: $DANGLING" >> "$LOG_FILE"

# Remove unused images (not referenced by any container)
IMAGES=$(docker image prune -a -f --filter "until=2h" 2>&1)
echo "[$TIMESTAMP] Unused images: $IMAGES" >> "$LOG_FILE"

# Remove unused volumes
VOLUMES=$(docker volume prune -f 2>&1)
echo "[$TIMESTAMP] Volumes: $VOLUMES" >> "$LOG_FILE"

# Remove unused networks
NETWORKS=$(docker network prune -f 2>&1)
echo "[$TIMESTAMP] Networks: $NETWORKS" >> "$LOG_FILE"

echo "[$TIMESTAMP] Cleanup complete." >> "$LOG_FILE"
