#!/bin/sh

# Delete all stopped containers more than a day old (including data-only containers).
docker ps -a -q --no-trunc --filter "status=exited" --format '{{.ID}} {{.Status}}' \
    | grep days | awk '{print $1}' | xargs --no-run-if-empty docker rm -v || true

if ! [[ $(ps aux | grep "[d]ocker build") ]]; then
    # Delete all dangling images more than a day old
    docker images -q --no-trunc --filter dangling=true --format '{{.ID}} {{.CreatedSince}} {{.Repository}}' \
        | grep -e ' days ago' | awk '{ print $1 }' \
        | xargs --no-run-if-empty docker rmi || true
fi

# Delete all tagged images more than a week old
docker images --no-trunc --format '{{.ID}} {{.CreatedSince}} {{.Repository}}' \
    | grep -v '/build-' | grep -v nginx | grep -e ' weeks ago' -e ' months ago' | awk '{ print $1 }' \
    | xargs --no-run-if-empty docker rmi || true
