---
# gitea-cleanup.yml — Weekly cleanup of Gitea server disk space
#
# Removes stale Docker buildx volumes, unused images, Gitea repo-archive
# cache, and vacuums journal logs to prevent disk exhaustion on LXC 225.
#
# Schedule: Weekly via systemd timer on LXC 304 (ansible-controller)
#
# Usage:
#   ansible-playbook /opt/ansible/playbooks/gitea-cleanup.yml          # full run
#   ansible-playbook /opt/ansible/playbooks/gitea-cleanup.yml --check  # dry run

- name: Gitea server disk cleanup
  hosts: gitea
  gather_facts: false

  tasks:
    - name: Check current disk usage
      ansible.builtin.shell: df --output=pcent / | tail -1
      register: disk_before
      changed_when: false

    - name: Display current disk usage
      ansible.builtin.debug:
        msg: "Disk usage before cleanup: {{ disk_before.stdout | trim }}"

    - name: Clear Gitea repo-archive cache
      ansible.builtin.find:
        paths: /var/lib/gitea/data/repo-archive
        file_type: any
      register: repo_archive_files

    - name: Remove repo-archive files
      ansible.builtin.file:
        path: "{{ item.path }}"
        state: absent
      loop: "{{ repo_archive_files.files }}"
      loop_control:
        label: "{{ item.path | basename }}"
      when: repo_archive_files.files | length > 0

    - name: Remove orphaned Docker buildx volumes
      ansible.builtin.shell: |
        volumes=$(docker volume ls -q --filter name=buildx_buildkit)
        if [ -n "$volumes" ]; then
          echo "$volumes" | xargs docker volume rm 2>&1
        else
          echo "No buildx volumes to remove"
        fi
      register: buildx_cleanup
      changed_when: "'No buildx volumes' not in buildx_cleanup.stdout"

    - name: Prune unused Docker images
      ansible.builtin.command: docker image prune -af
      register: image_prune
      changed_when: "'Total reclaimed space: 0B' not in image_prune.stdout"

    - name: Prune unused Docker volumes
      ansible.builtin.command: docker volume prune -f
      register: volume_prune
      changed_when: "'Total reclaimed space: 0B' not in volume_prune.stdout"

    - name: Vacuum journal logs to 500M
      ansible.builtin.command: journalctl --vacuum-size=500M
      register: journal_vacuum
      changed_when: "'freed 0B' not in journal_vacuum.stderr"

    - name: Check disk usage after cleanup
      ansible.builtin.shell: df --output=pcent / | tail -1
      register: disk_after
      changed_when: false

    - name: Display cleanup summary
      ansible.builtin.debug:
        msg: >-
          Cleanup complete.
          Disk: {{ disk_before.stdout | default('N/A') | trim }} → {{ disk_after.stdout | default('N/A') | trim }}.
          Buildx: {{ (buildx_cleanup.stdout_lines | default(['N/A'])) | last }}.
          Images: {{ (image_prune.stdout_lines | default(['N/A'])) | last }}.
          Journal: {{ (journal_vacuum.stderr_lines | default(['N/A'])) | last }}.
