---
- name: Check if certificates already exists
  stat:
    path: "{{ local_certs_path }}"
  register: certificates_folder
  delegate_to: localhost
  become: no
  tags:
    - generate-certs


- block:

  - name: Local action | Create local temporary directory for certificates generation
    file:
      path: "{{ local_certs_path }}"
      mode: 0755
      state: directory

  - name: Local action | Check that the generation tool exists
    stat:
      path: "{{ local_certs_path }}/wazuh-certs-tool.sh"
    register: tool_package

  - name: Local action | Download certificates generation tool
    get_url:
      url: "{{ certs_gen_tool_url }}"
      dest: "{{ local_certs_path }}/wazuh-certs-tool.sh"
    when: not tool_package.stat.exists

  - name: Local action | Prepare the certificates generation template file
    template:
      src: "templates/config.yml.j2"
      dest: "{{ local_certs_path }}/config.yml"
      mode: 0644
    register: tlsconfig_template

  - name: Local action | Generate the node & admin certificates in local
    command: >-
      bash {{ local_certs_path }}/wazuh-certs-tool.sh -A

  run_once: true
  delegate_to: localhost
  become: no
  tags:
    - generate-certs
  when:
    - not certificates_folder.stat.exists
