---

- include_tasks: ../shared/sync_file.yml
  vars:
    sync_file: "{{ item }}"
    sync_file_dir: "{{ vault_secrets_dir }}"
    sync_file_hosts: "{{ groups.vault }}"
  with_items:
    - root_token
    - unseal_keys

- name: bootstrap/sync_secrets | Set fact based on sync_file_results
  set_fact:
    vault_secrets_available: "{{ vault_secrets_available|default(true) and not item.no_srcs }}"
  with_items: "{{ sync_file_results|d([]) }}"

- name: bootstrap/sync_secrets | Reset sync_file_results to avoid variable bleed
  set_fact:
    sync_file_results: []

- name: bootstrap/sync_secrets | Print out warning message if secrets are not available and vault is initialized
  pause:
    prompt: >
          Vault orchestration may not be able to proceed. The Vault cluster is initialized, but
          'root_token' or 'unseal_keys' were not found in {{ vault_secrets_dir }}. These are
          needed for many vault orchestration steps.
  when: vault_cluster_is_initialized and not vault_secrets_available

- name: bootstrap/sync_secrets | Cat root_token from a vault host
  command: "cat {{ vault_secrets_dir }}/root_token"
  register: vault_root_token_cat
  run_once: yes
  when: vault_secrets_available

- name: bootstrap/sync_secrets | Cat unseal_keys from a vault host
  command: "cat {{ vault_secrets_dir }}/unseal_keys"
  register: vault_unseal_keys_cat
  run_once: yes
  when: vault_secrets_available

- name: bootstrap/sync_secrets | Set needed facts for Vault API interaction when Vault is already running
  set_fact:
    vault_root_token: "{{ vault_root_token_cat.stdout }}"
    vault_unseal_keys: "{{ vault_unseal_keys_cat.stdout_lines }}"
  run_once: yes
  when: vault_secrets_available

# FIXME: Remove all uri calls
- name: bootstrap/sync_secrets | Update vault_headers if we have the root_token
  set_fact:
    vault_headers: "{{ vault_client_headers | combine({'X-Vault-Token': vault_root_token}) }}"
  when: vault_secrets_available
