---
# Monthly Docker Prune — Deploy Cleanup Cron to All Docker Hosts
#
# Deploys /etc/cron.monthly/docker-prune to each VM running Docker.
# The script prunes stopped containers, unused images, and orphaned volumes
# older than 30 days (720h). Volumes labeled `keep` are exempt.
#
# Resolves accumulated disk waste from stopped containers and stale images.
# The `--filter "until=720h"` age gate prevents removing recently-pulled
# images that haven't started yet. `docker image prune -a` only removes
# images not referenced by any container (running or stopped), so the
# age filter adds an extra safety margin.
#
# Hosts: VM 106 (docker-home), VM 110 (discord-bots), VM 112 (databases-bots),
#        VM 115 (docker-sba), VM 116 (docker-home-servers), manticore
#
# Controller: LXC 304 (ansible-controller) at 10.10.0.232
#
# Usage:
#   # Dry run (shows what would change, skips writes)
#   ansible-playbook /opt/ansible/playbooks/docker-prune.yml --check
#
#   # Single host
#   ansible-playbook /opt/ansible/playbooks/docker-prune.yml --limit docker-sba
#
#   # All Docker hosts
#   ansible-playbook /opt/ansible/playbooks/docker-prune.yml
#
# To undo: rm /etc/cron.monthly/docker-prune on target hosts

- name: Deploy Docker monthly prune cron to all Docker hosts
  hosts: docker-home:discord-bots:databases-bots:docker-sba:docker-home-servers:manticore
  become: true

  tasks:
    - name: Deploy docker-prune cron script
      ansible.builtin.copy:
        dest: /etc/cron.monthly/docker-prune
        owner: root
        group: root
        mode: "0755"
        content: |
          #!/bin/bash
          # Monthly Docker cleanup — deployed by Ansible (issue #29)
          # Prunes stopped containers, unused images (>30 days), and orphaned volumes.
          # Volumes labeled `keep` are exempt from volume pruning.
          set -euo pipefail

          docker container prune -f --filter "until=720h"
          docker image prune -a -f --filter "until=720h"
          docker volume prune -f --filter "label!=keep"

    - name: Verify docker-prune script is executable
      ansible.builtin.command: test -x /etc/cron.monthly/docker-prune
      changed_when: false
