---
- name: Creating Murano database
  command: docker exec -t kolla_ansible /usr/bin/ansible localhost
    -m mysql_db
    -a "login_host='{{ database_address }}'
        login_user='{{ database_user }}'
        login_port='{{ mariadb_port }}'
        login_password='{{ database_password }}'
        name='{{ murano_database_name }}'"
  register: database
  changed_when: "{{ database.stdout.find('localhost | SUCCESS => ') != -1 and (database.stdout.split('localhost | SUCCESS => ')[1]|from_json).changed }}"
  failed_when: database.stdout.split()[2] != 'SUCCESS'
  run_once: True

- name: Creating Murano database user and setting permissions
  command: docker exec -t kolla_ansible /usr/bin/ansible localhost
    -m mysql_user
    -a "login_host='{{ database_address }}'
        login_user='{{ database_user }}'
        login_password='{{ database_password }}'
        name='{{ murano_database_name }}'
        password='{{ murano_database_password }}'
        host='%'
        priv='{{ murano_database_name }}.*:ALL'
        append_privs='yes'"
  register: database_user_create
  changed_when: "{{ database_user_create.stdout.find('localhost | SUCCESS => ') != -1 and (database_user_create.stdout.split('localhost | SUCCESS => ')[1]|from_json).changed }}"
  failed_when: database_user_create.stdout.split()[2] != 'SUCCESS'
  run_once: True

- name: Starting Murano bootstrap container
  docker:
    tty: True
    detach: False
    net: host
    pull: "{{ docker_pull_policy }}"
    restart_policy: "no"
    state: reloaded
    registry: "{{ docker_registry }}"
    username: "{{ docker_registry_username }}"
    password: "{{ docker_registry_password }}"
    insecure_registry: "{{ docker_insecure_registry }}"
    name: bootstrap_murano
    image: "{{ murano_api_image_full }}"
    volumes: "{{ node_config_directory }}/murano-api/:{{ container_config_directory }}/:ro"
    env:
      KOLLA_BOOTSTRAP:
      KOLLA_CONFIG_STRATEGY: "{{ config_strategy }}"
  run_once: True
  when:
    - database.stdout.find('localhost | SUCCESS => ') != -1 and (database.stdout.split('localhost | SUCCESS => ')[1]|from_json).changed
    - inventory_hostname in groups['murano-api']

# https://github.com/ansible/ansible-modules-core/pull/1031
- name: Waiting for bootstrap container to exit
  command: docker wait bootstrap_murano
  run_once: True
  when:
    - database.stdout.find('localhost | SUCCESS => ') != -1 and (database.stdout.split('localhost | SUCCESS => ')[1]|from_json).changed
    - inventory_hostname in groups['murano-api']

- name: Cleaning up Murano boostrap container
  docker:
    tty: True
    name: bootstrap_murano
    image: "{{ murano_api_image_full }}"
    state: absent
  when: database.stdout.find('localhost | SUCCESS => ') != -1 and (database.stdout.split('localhost | SUCCESS => ')[1]|from_json).changed
