#!/bin/bash
# Usage: ./clean_dockers.sh [-y] [--volumes]
#   -y         skip confirmation
#   --volumes  also delete volumes (data loss!)

RED='\033[0;31m'
GREEN='\033[0;32m'
CYAN='\033[0;36m'
YELLOW='\033[1;33m'
BOLD='\033[1m'
RESET='\033[0m'

section() { echo -e "\n${BOLD}${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n $1${RESET}"; }
ok()   { echo -e "  ${GREEN}✔ $1${RESET}"; }
warn() { echo -e "  ${YELLOW}⚠ $1${RESET}"; }
bad()  { echo -e "  ${RED}✘ $1${RESET}"; }

yes=0; volumes=0
for arg in "$@"; do
    case "$arg" in
        -y) yes=1 ;;
        --volumes) volumes=1 ;;
        *) bad "Unknown option: $arg"; exit 1 ;;
    esac
done

if ! docker info &>/dev/null; then
    bad "Docker is not running (or no permission)"
    exit 1
fi

section "🐳 DOCKER BEFORE"
docker system df

containers=$(docker ps -aq)
images=$(docker images -aq | sort -u)

echo
warn "Will delete: $(echo "$containers" | grep -c .) container(s), $(echo "$images" | grep -c .) image(s), build cache, unused networks"
(( volumes )) && warn "…and ALL volumes (data loss!)"

if (( ! yes )); then
    read -rp "  Continue? [y/N] " answer
    [[ "$answer" =~ ^[Yy]$ ]] || { echo "  Aborted."; exit 0; }
fi

section "🧹 CLEANING"

if [ -n "$containers" ]; then
    docker stop $containers &>/dev/null
    docker rm -f $containers &>/dev/null && ok "Containers removed" || bad "Some containers could not be removed"
else
    ok "No containers"
fi

if [ -n "$images" ]; then
    docker rmi -f $images &>/dev/null && ok "Images removed" || bad "Some images could not be removed"
else
    ok "No images"
fi

docker builder prune -af &>/dev/null && ok "Build cache cleared"
docker network prune -f &>/dev/null && ok "Unused networks removed"

if (( volumes )); then
    vols=$(docker volume ls -q)
    if [ -n "$vols" ]; then
        docker volume rm -f $vols &>/dev/null && ok "Volumes removed" || bad "Some volumes could not be removed"
    else
        ok "No volumes"
    fi
fi

section "🐳 DOCKER AFTER"
docker system df
echo
