---
- name: Fetch glusterfs plugin state
  block:
    - name: Fetch glusterfs storage plugin state
      ansible.builtin.command:
        cmd: docker plugin inspect glusterfs
      changed_when: false
      register: _docker_glusterfs_storage_plugin_raw
  rescue:
    - name: Install glusterfs storage plugin
      ansible.builtin.command:
        cmd: docker plugin install --alias glusterfs mochoa/glusterfs-volume-plugin --grant-all-permissions --disable
      changed_when: true

    - name: Fetch glusterfs storage plugin state
      ansible.builtin.command:
        cmd: docker plugin inspect glusterfs
      changed_when: false
      register: _docker_glusterfs_storage_plugin_raw

- name: Process glusterfs storage plugin config
  ansible.builtin.set_fact:
    _docker_glusterfs_storage_plugin: "{{ (_docker_glusterfs_storage_plugin_raw.stdout | from_json)[0] }}"

# Note that this might not end up being defined if the plugin has not been configured
- name: Identify plugin server settings
  when: item.startswith('SERVERS')
  ansible.builtin.set_fact:
    _docker_glusterfs_existing_setting: "{{ item }}"
  loop: "{{ _docker_glusterfs_storage_plugin.Settings.Env }}"

- name: Determine gluster servers
  run_once: true
  vars:
    _docker_glusterfs_hostnames: []
  ansible.builtin.set_fact:
    _docker_glusterfs_hostnames: "{{ _docker_glusterfs_hostnames + [item + '.local'] }}"
  loop: "{{ groups.cluster }}"

- name: Determine gluster plugin setting
  ansible.builtin.set_fact:
    _docker_glusterfs_setting: "SERVERS={{ _docker_glusterfs_hostnames | join(',') }}"

- name: Configure plugin
  when: _docker_glusterfs_setting != _docker_glusterfs_existing_setting
  block:
    - name: Disable plugin
      when: _docker_glusterfs_storage_plugin.Enabled
      ansible.builtin.command:
        cmd: docker plugin disable glusterfs

    - name: Set plugin servers setting
      changed_when: true
      ansible.builtin.command:
        cmd: docker plugin set glusterfs {{ _docker_glusterfs_setting }}
      register: _docker_glusterfs_set_setting

- name: Enable plugin
  when: not _docker_glusterfs_storage_plugin.Enabled or _docker_glusterfs_set_setting.changed | default(false)
  ansible.builtin.command:
    cmd: docker plugin enable glusterfs
