---
# Backup all docker-compose configs and data
- name: Backup Docker configurations
  hosts: "{{ target_host | default('all') }}"
  gather_facts: true

  vars:
    backup_dest: "{{ backup_path | default('/backup') }}"
    backup_timestamp: "{{ ansible_date_time.date }}_{{ ansible_date_time.hour }}{{ ansible_date_time.minute }}"

  tasks:
    - name: Create backup directory
      ansible.builtin.file:
        path: "{{ backup_dest }}/{{ inventory_hostname }}"
        state: directory
        mode: '0755'
      become: "{{ ansible_become | default(false) }}"
      delegate_to: localhost

    - name: Find all docker-compose files
      ansible.builtin.find:
        paths: "{{ docker_data_path }}"
        patterns: "docker-compose.yml,docker-compose.yaml,.env"
        recurse: true
      register: compose_files

    - name: Archive docker configs
      ansible.builtin.archive:
        path: "{{ docker_data_path }}"
        dest: "/tmp/{{ inventory_hostname }}_configs_{{ backup_timestamp }}.tar.gz"
        format: gz
        exclude_path:
          - "*/data/*"
          - "*/logs/*"
          - "*/cache/*"
      become: "{{ ansible_become | default(false) }}"

    - name: Fetch backup to control node
      ansible.builtin.fetch:
        src: "/tmp/{{ inventory_hostname }}_configs_{{ backup_timestamp }}.tar.gz"
        dest: "{{ backup_dest }}/{{ inventory_hostname }}/"
        flat: true

    - name: Clean up remote archive
      ansible.builtin.file:
        path: "/tmp/{{ inventory_hostname }}_configs_{{ backup_timestamp }}.tar.gz"
        state: absent
      become: "{{ ansible_become | default(false) }}"
