- name: Setup docker
  become: "{{ false if inventory_hostname == 'nas.home.lan' else true }}"
  collections:
    - community.docker
  block:
    - name: Facts
      ansible.builtin.setup:
      when: ansible_facts.architecture is not defined

    - name: Install docker SDK
      ansible.builtin.apt:
        name: python3-docker
        state: present

    - name: Set master host variable
      set_fact:
        master_host: "{{ (ansible_distribution | lower) ~ ansible_distribution_major_version ~ '-vm01.home.lan' }}"

    - name: Initialize swarm
      docker_swarm:
        state: present
        listen_addr: "{{ ansible_default_ipv4.address }}:2377"
      register: swarm_init
      when: inventory_hostname == master_host 

    - name: Show join tokens
      ansible.builtin.debug:
        msg:
          - "Manager join token: {{ swarm_init.swarm_facts['JoinTokens']['Manager'] }}"
          - "Worker join token: {{ swarm_init.swarm_facts['JoinTokens']['Worker'] }}"
      when: inventory_hostname == master_host

    - name: Join swarm as worker
      shell: docker swarm join --token {{ hostvars[master_host]['swarm_init'].swarm_facts['JoinTokens']['Worker'] }} {{ hostvars[master_host]['ansible_default_ipv4']['address'] }}:2377
      when: inventory_hostname != master_host 