---
- name: Fetch join token from existing manager
  delegate_to: "{{ _docker_swarm_manager }}"
  changed_when: false
  ansible.builtin.command:
    cmd: docker swarm join-token manager --quiet
  register: _docker_swarm_join_token

- name: Fetch manager addresses from existing manager
  delegate_to: "{{ _docker_swarm_manager }}"
  changed_when: false
  ansible.builtin.command:
    cmd: !unsafe docker info --format '{{json .Swarm.RemoteManagers}}'
  register: _docker_swarm_manager_info_raw

- name: Process manager addresses
  vars:
    _docker_swarm_manager_addresses: []
  ansible.builtin.set_fact:
    _docker_swarm_manager_addresses: "{{ _docker_swarm_manager_addresses + [item.Addr] }}"
  loop: "{{ _docker_swarm_manager_info_raw.stdout | from_json }}"

- name: Join node to swarm
  vars:
    ansible_python_interpreter: "{{ skylab_ansible_venv }}/bin/python"
  community.docker.docker_swarm:
    state: join
    advertise_addr: "{{ lookup('vars', 'ansible_' + skylab_cluster.interface.internal).ipv4.address }}"
    listen_addr: "{{ lookup('vars', 'ansible_' + skylab_cluster.interface.internal).ipv4.address }}"
    remote_addrs: "{{ _docker_swarm_manager_addresses }}"
    join_token: "{{ _docker_swarm_join_token.stdout.strip() }}"
    timeout: 1200

- name: Fetch node swarm ID
  ansible.builtin.command:
    cmd: !unsafe docker info --format '{{ .Swarm.NodeID}}'
  changed_when: false
  register: _docker_node_id_raw

# For newly added nodes we don't want to have services be automatically scheduled on them
# until the configuration is complete. The node-up playbook will be responsible for updating
# the node to make it available in the cluster again
- name: Update node to drain
  vars:
    ansible_python_interpreter: "{{ skylab_ansible_venv }}/bin/python"
  community.docker.docker_node:
    availability: drain
    hostname: "{{ _docker_node_id_raw.stdout.strip() }}"
