#!/bin/bash

echo "🚀 Starting Docker cleanup script..."

# 1. 清理已停止的容器
echo "➡️  Step 1: Removing all stopped containers..."
# -f: 强制删除
# docker ps -a -q: 列出所有容器（包括已停止的），并只显示ID
docker container prune -f
echo "✅ Done. Stopped containers have been removed."

# 2. 清理未使用的网络
echo "➡️  Step 2: Removing unused networks..."
docker network prune -f
echo "✅ Done. Unused networks have been removed."

# 3. 清理所有未使用的镜像
echo "➡️  Step 3: Removing all unused images..."
# docker image prune -a: -a 参数会删除所有未被任何容器引用的镜像，包括有标签的。
docker image prune -a -f
echo "✅ Done. All unused images have been removed."

# 4. 清理所有未使用的卷
echo "➡️  Step 4: Removing unused volumes..."
# 警告：卷通常用于持久化数据，请确保其中的数据不再需要。
docker volume prune -f
echo "✅ Done. Unused volumes have been removed."

# 5. 清理 Docker 构建缓存
echo "➡️  Step 5: Cleaning up Docker build cache..."
docker builder prune -f
echo "✅ Done. Build cache has been cleared."

# 6. 一键式清理，以防有遗漏
echo "➡️  Step 6: Running a final system-wide prune for good measure..."
docker system prune -a -f
echo "✅ Done. The final system prune is complete."

# 检查是否以 root 权限运行
if [ "$EUID" -ne 0 ]; then
  echo "⚠️ This script requires root privileges. Please run with 'sudo'."
  exit 1
fi

echo "➡️  Truncating log files for all containers..."

# 使用 docker inspect 命令获取日志文件的完整路径
for container_id in $(docker ps -aq); do
    log_path=$(docker inspect --format='{{.LogPath}}' "$container_id")
    if [ -f "$log_path" ]; then
        log_size=$(du -sh "$log_path" | cut -f1)
        if [ "$log_size" != "0" ]; then
            echo "   - Cleaning log file for container ID: $container_id (Size: $log_size)"
            truncate -s 0 "$log_path"
        fi
    fi
done

echo "🎉 Docker cleanup finished! Checking disk usage again..."
df -h /var/lib/docker