---
- name: "Ensure output dirs exist"
  file:
    state: directory
    path: '{{ item }}'
  loop:
    - '{{ docker_compose_output }}'
    - '{{ vault_config_output }}'
    - '{{ mmock_config_path }}'
    - '{{ postgres_config_path }}'

- name: "Create the docker-compose definition"
  template:
    src: docker-compose.yml.j2
    dest: '{{ docker_compose_file }}'

- name: "Persist vars (role_path is relative)"
  set_fact:
    vault_cert_file: '{{ vault_cert_file }}'
    vault_key_file: '{{ vault_key_file }}'

- name: "Check if cert already exists"
  stat:
    path: '{{ vault_cert_file }}'
    follow: true
    get_attributes: false
    get_checksum: false
    get_mime: false
  register: cert_status

- name: "Check if key already exists"
  stat:
    path: '{{ vault_key_file }}'
    follow: true
    get_attributes: false
    get_checksum: false
    get_mime: false
  register: key_status

- name: "Generate certs"
  when: >-
    vault_crypto_force | bool
    or not (key_status.stat.exists and cert_status.stat.exists)
  include_role:
    name: setup_vault_server_cert
  vars:
    vault_dns_names: '{{ [vault_target_name, vault_container_name] | unique }}'

- name: "Template vault config"
  template:
    src: vault_config.hcl.j2
    dest: '{{ vault_config_output }}/vault_config.hcl'

- name: "Template mmock configs"
  loop: "{{ query('fileglob', role_path ~ '/templates/mmock/*.j2') }}"
  loop_control:
    label: '{{ dest_name }}'
  vars:
    dest_name: '{{ item | basename | splitext | first }}'
  template:
    src: '{{ item }}'
    dest: '{{ mmock_config_path }}/{{ dest_name }}'

- name: "Template integration_config"
  template:
    src: integration_config.yml.j2
    dest: '{{ output_dir }}/integration_config.yml'
    force: true

- name: "Copy postgres init.sql script"
  copy:
    src: files/sql/init.sql
    dest: "{{ postgres_config_path }}/init.sql"
    force: true

- include_tasks: docker.yml
  when: docker_compose != 'none'
