---
# Watch repositories task to retrieve repository add
- name: Check Elastic Search installation
  shell: apt-cache policy elasticsearch | grep -Po 'Installed:\s(.*)' | cut -d' ' -f 2;
  changed_when: false
  register: install_status

- name: Set installed variable
  set_fact: is_installed='{{ install_status.stdout == elasticsearch.version }}'

- name: Set dependencies License
  shell: echo debconf shared/accepted-oracle-license-v1-1 select true | sudo debconf-set-selections
  changed_when: false

- name: Install Dependencies
  apt: pkg=openjdk-8-jre state=latest

- name: Remove temporary debian package
  shell: rm -f /tmp/elasticsearch-{{ elasticsearch.version }}.deb
  when: not is_installed

- name: Download debian package
  get_url: >
    url={{ elasticsearch_url }}
    dest=/tmp/elasticsearch-{{ elasticsearch.version }}.deb
  when: not is_installed

- name: Install debian package
  apt: deb=/tmp/elasticsearch-{{ elasticsearch.version }}.deb
  when: not is_installed

- name: Remove old plugin directory
  shell: rm -rf /usr/share/elasticsearch/plugins/analysis-icu
  sudo: yes

- name: Install plugins
  shell: /usr/share/elasticsearch/bin/plugin install {{ item.name }}
  when: not is_installed
  with_items: "{{ elasticsearch.plugins }}"

- name: Configure Elasticsearch.
  lineinfile:
    dest: /etc/elasticsearch/elasticsearch.yml
    regexp: "{{ item.regexp }}"
    line: "{{ item.line }}"
    state: present
  with_items:
    - { regexp: '^#? ?network\.host', line: 'network.host: {{ elasticsearch.host }}' }
    - { regexp: '^#? ?http\.port', line: 'http.port: {{ elasticsearch.port }}' }

- name: Flush handlers to apply config changes
  meta: flush_handlers

- name: Enable Service
  service: name=elasticsearch enabled=yes

- name: Ensure Elastic Search is started
  service: name=elasticsearch state=started

- name: Remove tmp files
  file: path=/tmp/elasticsearch-{{ elasticsearch.version }}.deb state=absent
  when: not is_installed
