---
- name: Add Docker repository
  ansible.builtin.get_url:
    url: https://download.docker.com/linux/rhel/docker-ce.repo
    dest: /etc/yum.repos.d/docker-ce.repo
    mode: '0644'

- name: Install Docker packages
  ansible.builtin.dnf:
    name:
      - docker-ce
      - docker-ce-cli
      - containerd.io
      - docker-buildx-plugin
      - docker-compose-plugin
    state: present

- name: Ensure /etc/docker directory exists
  ansible.builtin.file:
    path: /etc/docker
    state: directory
    mode: '0755'

- name: Configure Docker daemon (Log Rotation)
  ansible.builtin.template:
    src: daemon.json.j2
    dest: /etc/docker/daemon.json
    mode: '0644'
  notify: Restart Docker

- name: Ensure Docker is started and enabled
  ansible.builtin.service:
    name: docker
    state: started
    enabled: yes

- name: Allow Docker Swarm ports in firewalld (all nodes)
  ansible.posix.firewalld:
    port: "{{ item }}"
    permanent: yes
    immediate: yes
    state: enabled
  loop:
    - 2377/tcp
    - 7946/tcp
    - 7946/udp
    - 4789/udp

- name: Allow web ports in firewalld (app nodes only)
  ansible.posix.firewalld:
    port: "{{ item }}"
    permanent: yes
    immediate: yes
    state: enabled
  loop:
    - 80/tcp
    - 443/tcp
  when: inventory_hostname in groups['app']
