---
# ensure that the underlying config is correct

- name: fetch details
  block:

    - name: get old node UUID
      ansible.builtin.shell: |
        gluster pool list | grep {{ new_node }} | awk '{print $1}'
      register: old_node_uuid
      changed_when: false

    - debug:
        var: "old_node_uuid.stdout"
      when: old_node_uuid is defined

  become: true
  when: inventory_hostname != new_node.name

- name: update new node
  block:
    - name: stop glusterd
      ansible.builtin.service:
        name: "{{ glusterfs_daemon }}"
        state: stopped
      changed_when: false

    - name: update glusterd.info
      ansible.builtin.lineinfile:
        path: /var/lib/glusterd/glusterd.info
        regexp: '^UUID='
        line: 'UUID={{ new_node.uuid }}'

    - name: start glusterd
      ansible.builtin.service:
        name: "{{ glusterfs_daemon }}"
        state: started
      changed_when: false

    - name: add cluster nodes to new node
      ansible.builtin.shell: "gluster peer probe {{ item }}"
      register: peer_probe_result
      with_items: cluster
      changed_when:
        - "'already in peer list' not in peer_probe_result.stdout"
        - "'peer probe: success' in peer_probe_result.stdout"
      failed_when: false

    - name: reset systemctl restart count
      ansible.builtin.shell: "systemctl reset-failed {{ glusterfs_daemon }}"
      changed_when: false

    - name: retart glusterd
      ansible.builtin.service:
        name: "{{ glusterfs_daemon }}"
        state: restarted
      changed_when: false


#    - name: add volumes
#      ansible.builtin.shell: "gluster --mode=script volume sync {{ cluster[0] }} tmp"
#      register: sync_result
#      failed_when: "'volume sync: success' not in sync_result"

  become: true
  when: inventory_hostname == new_node.name


- name: create tmp gluster volume
  gluster_volume:
    state: present
    start_on_create: yes
    name: "tmp"
    brick: '/data/glusterfs/tmp/brick1'
    rebalance: no
    replicas: 2
    force: true
    cluster:
      - home
      - cubox-i
  run_once: true
