---
- name: Online nodes
  hosts: cluster
  vars_prompt:
    - name: skylab_datastore_encryption_password
      prompt: Enter datastore block decryption password
      private: true
  pre_tasks:
    - name: Configure remote execution environment
      ansible.builtin.import_tasks: tasks/meta/bootstrap-remote-env.yaml
  roles:
    - role: skylab.core.datastore
  tasks:
    - name: Fetch node swarm ID
      ansible.builtin.command:
        cmd: !unsafe docker info --format '{{ .Swarm.NodeID}}'
      changed_when: false
      register: _docker_node_id_raw

    - name: Update node availability
      vars:
        ansible_python_interpreter: "{{ skylab_state_dir }}/ansible-runtime/bin/python"
      community.docker.docker_node:
        availability: active
        hostname: "{{ _docker_node_id_raw.stdout.strip() }}"

    - name: Determine node addresses
      vars:
        _node_addresses:
          - "{{ (lookup('vars', 'ansible_' + skylab_cluster.interface.access).ipv4.address + '/' + lookup('vars', 'ansible_' + skylab_cluster.interface.access).ipv4.netmask) | ansible.netcommon.ipaddr('host/prefix') }}"
      ansible.builtin.set_fact:
        _node_addresses: "{{ _node_addresses + [(item.address + '/' + item.netmask) | ansible.netcommon.ipaddr('host/prefix')] }}"
      loop: "{{ lookup('vars', 'ansible_' + skylab_cluster.interface.access).ipv4_secondaries }}"
      loop_control:
        label: "{{ (item.address + '/' + item.netmask) | ansible.netcommon.ipaddr('host/prefix') }}"

    - name: Determine cluster access addresses
      run_once: true
      vars:
        _cluster_node_ips: []
      ansible.builtin.set_fact:
        _cluster_node_ips: "{{ _cluster_node_ips + [hostvars[item].skylab_cluster.address.access | ansible.netcommon.ipaddr('host/prefix')] }}"
      loop: "{{ groups.cluster }}"

    - name: Remove alternative node IPs
      become: true
      when: item in _cluster_node_ips and item != (skylab_cluster.address.access | ansible.netcommon.ipaddr('host/prefix'))
      ansible.builtin.command:
        cmd: ip address delete {{ item | ansible.netcommon.ipaddr('host/prefix') }} dev {{ skylab_cluster.interface.access }}
      changed_when: true
      loop: "{{ _node_addresses }}"

    - name: Add node IP
      become: true
      when: skylab_cluster.address.access | ansible.netcommon.ipaddr('host/prefix') not in _node_addresses
      ansible.builtin.command:
        cmd: ip address add {{ skylab_cluster.address.access | ansible.netcommon.ipaddr('host/prefix') }} dev {{ skylab_cluster.interface.access }}
      changed_when: true
