---

### tags:
###   update_certs
###   update_config
###   update_deployment

- name: "Check if {{ elastic_id }}/docker-compose.yml exists"
  stat:
    path: '{{ service_base_path }}/{{ elastic_id }}/docker-compose.yml'
  register: check_docker_compose_file
  tags:
    - update_config
    - update_deployment

- name: "Stop {{ elastic_id }}"
  community.docker.docker_compose:
    project_src: '{{ service_base_path }}/{{ elastic_id }}'
    state: absent
  when: check_docker_compose_file.stat.exists
  tags:
    - update_config
    - update_deployment

- name: "Deploy docker templates for {{ elastic_id }}"
  include_role:
    name: hetzner-ansible-sma-deploy
    tasks_from: templates
  vars:
    current_config: "_docker"
    current_base_path: "{{ service_base_path }}"
    current_destination: "{{ elastic_id }}"
    current_owner: "{{ docker_owner }}"
    current_group: "{{ docker_group }}"
    current_docker: "{{ elastic_docker }}"
  tags:
    - update_config

- name: "Deploy service templates for {{ elastic_id }}"
  include_role:
    name: hetzner-ansible-sma-deploy
    tasks_from: templates
  vars:
    current_config: "elastic"
    current_base_path: "{{ service_base_path }}"
    current_destination: "{{ elastic_id }}"
    current_owner: "{{ docker_owner }}"
    current_group: "{{ docker_group }}"
  tags:
    - update_config

- name: "Deploy certificate templates for {{ elastic_id }}"
  include_role:
    name: hetzner-ansible-sma-deploy
    tasks_from: templates
  vars:
    current_config: "elastic-certs/{{ stage }}-certs"
    current_base_path: "{{ service_base_path }}"
    current_destination: "{{ elastic_id }}/certs"
    current_owner: "{{ docker_owner }}"
    current_group: "{{ docker_group }}"
    cleanup_destination: "true"
  tags:
    - update_certs
    - update_config

- name: "Restart {{ elastic_id }}"
  community.docker.docker_compose:
    project_src: '{{ service_base_path }}/{{ elastic_id }}'
    restarted: yes
    build: no
  tags:
    - update_certs

- name: "Update {{ elastic_id }}"
  community.docker.docker_compose:
    project_src: '{{ service_base_path }}/{{ elastic_id }}'
    state: present
    pull: yes
  tags:
    - update_config
    - update_deployment

- name: "Set VAR"
  set_fact:
    es_cluster_settings:
      persistent:
        cluster.max_shards_per_node: "{{ elastic_cluster_settings_max_shards }}"

- name: "Set cluster config"
  uri:
    url: "https://localhost:9200/_cluster/settings"
    method: PUT
    ca_path: "{{ service_base_path }}/{{ elastic_id }}/certs/ca/ca.crt"
    user: "{{ elastic_admin_username }}"
    password: "{{ elastic_admin_password }}"
    headers:
      Content-Type: "application/json"
      Accept: "application/json"
    body_format: "json"
    body: "{{ es_cluster_settings |to_json }}"
    force_basic_auth: true
    status_code: 200
  when:
    - inventory_hostname == groups['elastic'][0]
