#!/bin/bash
# DashCaddy Docker Space Management
# Runs via cron to keep Docker disk usage under control
# Prevents the overlay2 + dangling volumes + stale images that fill the disk

set -euo pipefail

MAX_DISK_PCT=85  # Alert if disk usage exceeds this
LOG_PREFIX="[dc-disk]"

# 1. Remove dangling (untagged) images
echo "$LOG_PREFIX Pruning dangling images..."
docker image prune -f --filter "dangling=true" 2>/dev/null || true

# 2. Remove unused volumes (volumes not attached to any container)
echo "$LOG_PREFIX Pruning unused volumes..."
docker volume prune -f 2>/dev/null || true

# 3. Remove old build cache
echo "$LOG_PREFIX Pruning build cache..."
docker builder prune -f --keep-storage 500m 2>/dev/null || true

# 4. Remove stopped containers older than 7 days
echo "$LOG_PREFIX Pruning old stopped containers..."
docker container prune -f --filter "until=168h" 2>/dev/null || true

# 5. Remove images not used by any container (keep only running images)
# Only remove images older than 7 days to avoid breaking recent updates
echo "$LOG_PREFIX Pruning unused images (>7 days old)..."
docker image prune -a -f --filter "until=168h" --filter "dangling=false" 2>/dev/null || true

# 6. Truncate container log files that are bigger than 100MB
echo "$LOG_PREFIX Checking container logs..."
for logfile in /var/lib/docker/containers/*/*-json.log; do
  if [ -f "$logfile" ]; then
    size=$(stat -c%s "$logfile" 2>/dev/null || echo 0)
    if [ "$size" -gt 104857600 ]; then  # 100MB
      echo "$LOG_PREFIX Truncating $(basename $logfile) ($(( size / 1048576 ))MB)"
      truncate -s 0 "$logfile"
    fi
  fi
done

# 7. Vacuum journald logs to 200MB
echo "$LOG_PREFIX Vacuuming journal logs..."
journalctl --vacuum-size=200M 2>/dev/null || true

# 8. Clear pip/npm caches that grow over time
echo "$LOG_PREFIX Clearing stale caches..."
rm -rf /root/.cache/pip/cache/html 2>/dev/null || true
rm -rf /root/.cache/npm/_cacache 2>/dev/null || true

# 9. Report disk usage
USAGE=$(df / | tail -1 | awk '{print $5}' | tr -d '%')
FREE_GB=$(df -h / | tail -1 | awk '{print $4}')
echo "$LOG_PREFIX Disk usage: ${USAGE}% (${FREE_GB} free)"

if [ "$USAGE" -gt "$MAX_DISK_PCT" ]; then
  echo "$LOG_PREFIX WARNING: Disk usage above ${MAX_DISK_PCT}%!"
  # More aggressive: remove ALL images not used by running containers
  echo "$LOG_PREFIX Aggressive prune: removing all unused images..."
  docker image prune -a -f 2>/dev/null || true
fi

echo "$LOG_PREFIX Done."
