---
# tasks file for ansible-role-mariadb

- name: Set db_main host variable
  set_fact:
    db_main: "{{ groups['db_servers'][0] }}"
    my_service: {"name": "mariadb.service", "source": "systemd", "state": "unknown", "status": "disabled"}

- name: Include OS specific variables.
  include_vars: "{{ ansible_os_family }}.yml"

- name: collect facts about system services
  service_facts:
  register: services_state

- name: Set db_main host variable
  set_fact:
    my_service: "{{ ansible_facts.services['mariadb.service'] }}"
  when: "'mariadb.service' in ansible_facts.services.keys()"

- name: Check Mariadb status
  debug:
    var: my_service

      #- name: Ending if Mariadb is already up and running
      #  meta: end_play
      #  when: my_service.state != "unknown" and my_service.status != "disabled"

- name: Install Mariadb
  include_tasks: "setup/{{ ansible_os_family }}.yml"
  when: my_service.state == "unknown" and my_service.status == "disabled"

- name: Ensure Mariadb configfile is present
  include_tasks: "config/template.yml"
  when: my_service.state == "unknown" and my_service.status == "disabled"

- name: Ensure Mariadb is secure
  include_tasks: "config/secure-installation.yml"

- name: Creating a SELinux Policy
  include_tasks: "selinux.yml"
  when: groups['db_servers'] | length > 1 and ( my_service.state == "unknown" and my_service.status == "disabled" )

- name: Bring Up the First Node
  shell: galera_new_cluster
  delegate_to: "{{ groups['db_servers'][0] }}"
  run_once: true
  when: groups['db_servers'] | length > 1 and ( my_service.state == "unknown" and my_service.status == "disabled" )

- name: Start the others Nodes
  service:
    name: "{{ mariadb_service }}"
    state: started
  when: inventory_hostname == item and ( my_service.state == "unknown" and my_service.status == "disabled" )
  with_items: "{{ groups['db_servers'] | reject('equalto', groups['db_servers'][0]) | list }}"
  loop_control:
    pause: 5

      #- name: Ensure Mariadb databases are present
      #  include_tasks: "database/databases.yml"

- name: Ensure Mariadb users are present
  include_tasks: "database/users.yml"
