---

- name: "User {{ elasticsearch_plugin_head_owner }} is present"
  user:
    name: "{{ elasticsearch_plugin_head_owner }}"
    home: "{{ elasticsearch_plugin_head_home }}"
    createhome: yes
    system: yes
    shell: /bin/false

- name: Head plugin is installed
  block:
    - name: Head repository is checked-out
      git:
        repo: "https://github.com/mobz/elasticsearch-head.git"
        dest: "{{ elasticsearch_plugin_head_clone_dir }}"
        clone: yes
      tags:
        - packages

    - name: Create tmpdir
      file:
        dest: "{{ elasticsearch_plugin_head_tmp_dir }}"
        state: directory

    - name: NPM packages for head are installed
      npm:
        path: "{{ elasticsearch_plugin_head_clone_dir }}"
      tags:
        - packages
        - npm
      environment:
        TMPDIR: "{{ elasticsearch_plugin_head_tmp_dir }}"
  become_user: "{{ elasticsearch_plugin_head_owner }}"
  become: yes

- name: Elasticsearch HTTP/CORS are enabled
  lineinfile:
    dest: /etc/elasticsearch/elasticsearch.yml
    line: "http.cors.enabled: true"
    regexp: "^http.cors.enabled:"
    insertafter: EOF
  notify:
    - restart elasticsearch
  tags:
    - elasticsearch

- name: Elasticsearch HTTP/CORS accepts all origins
  lineinfile:
    dest: /etc/elasticsearch/elasticsearch.yml
    line: "http.cors.allow-origin: \"*\""
    regexp: "^http.cors.allow-origin:"
    insertafter: "http.cors.enabled"
  notify:
    - restart elasticsearch
  tags:
    - elasticsearch

- name: Install systemd unit
  template:
    src: elasticsearch-head.service.j2
    dest: /etc/systemd/system/elasticsearch-head.service
  tags:
    - elasticsearch
    - systemd

- name: Enable systemd unit
  systemd:
    name: elasticsearch-head
    daemon_reload: yes
    enabled: yes
    state: started
  tags:
    - elasticsearch
    - systemd
