---

- name: Allow mysql to listen on tcp port 4567,4568,4444
  seport:
    ports: 4567,4568,4444
    proto: tcp
    setype: mysqld_port_t
    state: present

- name: Allow mysql to listen on udp port 4567
  seport:
    ports: 4567
    proto: udp
    setype: mysqld_port_t
    state: present

- name: Sets the MySQL SELinux domain to permissive mode temporarily
  command: semanage permissive -a mysqld_t

- name: Mariadb service
  service:
    name: "{{ mariadb_service }}"
    state: stopped

- name: Bootstrap the cluster
  command: galera_new_cluster
  delegate_to: "{{ groups['db_servers'][0] }}"

- name: Create a database for the specific purpose of logging SST events
  mysql_db:
    name: selinux
    state: present
  delegate_to: "{{ groups['db_servers'][0] }}"
  run_once: true

- name: Create a table for the specific purpose of logging SST events
  community.mysql.mysql_query:
    login_db: selinux
    query: "CREATE TABLE selinux.selinux_policy (id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id));"
  delegate_to: "{{ groups['db_servers'][0] }}"
  run_once: true

- name: Run insert queries against db selinux in single transaction
  community.mysql.mysql_query:
    login_db: selinux
    query: "INSERT INTO selinux.selinux_policy VALUES ();"
    single_transaction: yes
  delegate_to: "{{ groups['db_servers'][0] }}"
  run_once: true

- name: Mariadb service
  service:
    name: "{{ mariadb_service }}"
    state: started

- name: Generate IST events
  community.mysql.mysql_query:
    login_db: selinux
    query: "INSERT INTO selinux.selinux_policy VALUES ();"
    single_transaction: yes 

- name: Create and enable the SELinux policy
  shell: "grep mysql /var/log/audit/audit.log | audit2allow -M Galera"
  ignore_errors: yes

- name: Build and install Galera.pp
  shell: semodule -i Galera.pp
  ignore_errors: yes

- name: Disable permissive mode
  shell: semanage permissive -d mysqld_t

- name: Mariadb stop service
  service:
    name: "{{ mariadb_service }}"
    state: stopped

- name: Make Bootstrap safe
  lineinfile:
    dest: /var/lib/mysql/grastate.dat
    regexp: "^{{ item.property | regex_escape() }}.*"
    line: "{{ item.value }}"
  with_items:
    - { property: 'safe_to_bootstrap:', value: 'safe_to_bootstrap: 1' }
  delegate_to: "{{ groups['db_servers'][0] }}"
  run_once: true
