---
-
  name: Ensure replication user exists on master.
  community.mysql.mysql_user:
    name: "{{ mysql_replication_user.name }}"
    host: "{{ mysql_replication_user.host | default('%') }}"
    password: "{{ mysql_replication_user.password }}"
    priv: "{{ mysql_replication_user.priv | default('*.*:REPLICATION SLAVE,REPLICATION CLIENT') }}"
    state: present
  no_log: "{{ mysql_hide_passwords }}"
  when:
    - mysql_replication_role == 'master'
    - mysql_replication_user.name is defined
    - (mysql_replication_master | length) > 0
  tags: ['skip_ansible_galaxy']

-
  name: Check slave replication status.
  community.mysql.mysql_replication:
    mode: getreplica
    login_user: "{{ mysql_root_username }}"
    login_password: "{{ mysql_root_password }}"
  no_log: "{{ mysql_hide_passwords }}"
  ignore_errors: true
  register: slave
  when:
    - mysql_replication_role == 'slave'
    - (mysql_replication_master | length) > 0
  tags: ['skip_ansible_galaxy']

# https://github.com/ansible/ansible/issues/82264
-
  name: Check master replication status.
  community.mysql.mysql_replication:
    mode: getprimary
  delegate_to: "{{ mysql_replication_master_inventory_host | default(omit, true) }}"
  register: master
  when:
    - (slave.Is_Slave is defined and not slave.Is_Slave) or (slave.Is_Replica is defined and not slave.Is_Replica) or (slave.Is_Slave is not defined and slave.Is_Replica is not defined and slave is failed)
    - mysql_replication_role == 'slave'
    - (mysql_replication_master | length) > 0
  tags: ['skip_ansible_galaxy']

-
  name: Configure replication on the slave.
  community.mysql.mysql_replication:
    mode: changeprimary
    master_host: "{{ mysql_replication_master }}"
    master_user: "{{ mysql_replication_user.name }}"
    master_password: "{{ mysql_replication_user.password }}"
    master_log_file: "{{ master.File }}"
    master_log_pos: "{{ master.Position }}"
  no_log: "{{ mysql_hide_passwords }}"
  failed_when:
    - "'ERROR' in slave.msg"
    - slave.failed
  when:
    - (slave.Is_Slave is defined and not slave.Is_Slave) or (slave.Is_Replica is defined and not slave.Is_Replica) or (slave.Is_Slave is not defined and slave.Is_Replica is not defined and slave is failed)
    - mysql_replication_role == 'slave'
    - mysql_replication_user.name is defined
    - (mysql_replication_master | length) > 0

-
  name: Start replication.
  community.mysql.mysql_replication:
    mode: startreplica
  when:
    - (slave.Is_Slave is defined and slave.Is_Slave) or (slave.Is_Replica is defined and slave.Is_Replica) or (slave.Is_Slave is not defined and slave.Is_Replica is not defined and slave is failed)
    - mysql_replication_role == 'slave'
    - (mysql_replication_master | length) > 0
  tags: ['skip_ansible_galaxy']
