---

- name: cluster/init | wait for vault
  command: /bin/true
  notify: wait for vault up

- meta: flush_handlers

- name: cluster/init | Initialize Vault
  hashivault_init:
    url: "https://localhost:{{ vault_port }}/"
    ca_cert: "{{ vault_cert_dir }}/ca.pem"
    secret_shares: "{{ vault_secret_shares }}"
    secret_threshold: "{{ vault_secret_threshold }}"
  run_once: true
  register: vault_init_result
  when: not vault_cluster_is_initialized

- name: cluster/init | Set facts on the results of the initialization
  set_fact:
    vault_unseal_keys: "{{ vault_init_result.keys_base64 }}"
    vault_root_token: "{{ vault_init_result.root_token }}"
    vault_headers: "{{ vault_client_headers|combine({'X-Vault-Token': vault_init_result.root_token}) }}"
  run_once: true
  when: not vault_cluster_is_initialized

- name: cluster/init | Ensure all in groups.vault have the unseal_keys locally
  copy:
    content: "{{ vault_unseal_keys|join('\n') }}"
    dest: "{{ vault_secrets_dir }}/unseal_keys"
    mode: 0640
  when: not vault_cluster_is_initialized

- name: cluster/init | Ensure all in groups.vault have the root_token locally
  copy:
    content: "{{ vault_root_token }}"
    dest: "{{ vault_secrets_dir }}/root_token"
    mode: 0640
  when: not vault_cluster_is_initialized

- name: cluster/init | Ensure vault_headers and vault statuses are updated
  set_fact:
    vault_cluster_is_initialized: true
  run_once: true
