---

- name: Set real datadir value when customized
  block:
    - name: "Is custom datadir present ?"
      ansible.builtin.stat:
        path: "{{ elasticsearch_custom_datadir }}"
      register: elasticsearch_custom_datadir_test
      check_mode: no

    - name: "read the real datadir"
      ansible.builtin.command: readlink -f /var/lib/elasticsearch
      changed_when: False
      register: elasticsearch_current_real_datadir_test
      check_mode: no
  tags:
    - elasticsearch
  when:
    - elasticsearch_custom_datadir is not none
    - elasticsearch_custom_datadir | length > 0

- name: Datadir is moved to custom path
  block:
    - name: elasticsearch is stopped
      ansible.builtin.service:
        name: elasticsearch
        state: stopped

    - name: Move elasticsearch datadir to custom datadir
      ansible.builtin.command:
        cmd: mv {{ elasticsearch_current_real_datadir_test.stdout }} {{ elasticsearch_custom_datadir }}
      args:
        creates: "{{ elasticsearch_custom_datadir }}"

    - name: Symlink {{ elasticsearch_custom_datadir }} to /var/lib/elasticsearch
      ansible.builtin.file:
        src: "{{ elasticsearch_custom_datadir }}"
        dest: '/var/lib/elasticsearch'
        state: link

    - name: elasticsearch is started
      ansible.builtin.service:
        name: elasticsearch
        state: started
  tags:
    - elasticsearch
  when:
    - elasticsearch_custom_datadir is not none
    - elasticsearch_custom_datadir | length > 0
    - elasticsearch_custom_datadir != elasticsearch_current_real_datadir_test.stdout
    - not elasticsearch_custom_datadir_test.stat.exists
