---

- name: Ensure Mariadb users are present
  mysql_user:
    name: "{{ item.0.name }}"
    #host: "{{ item.1 }}"
    host: "%"
    password: "{{ item.0.pass }}"
    priv: "{{ item.0.name }}.{{ item.0.priv }}"
    state: "present"
    append_privs: "no"
    encrypted: "{{ mariadb_user_encrypted | default('no') }}"
    login_unix_socket: "{{ mariadb_socket }}"
  with_subelements:
    - "{{ mariadb_database }}"
    - hosts
  run_once: true
  no_log: true

    #- name: Allow previous user to ProxySQL
    #  mysql_user:
    #    name: "{{ item.0.name }}"
    #    host: "{{ groups['db_lbal_servers'][0] | default('localhost') }}"
    #    password: "{{ item.0.pass | default('sbpass') }}"
    #    priv: "*.*:ALL,GRANT"
    #    state: "present"
    #    append_privs: "no"
    #    encrypted: "{{ mariadb_user_encrypted | default('no') }}"
    #    login_unix_socket: "{{ mariadb_socket }}"
    #  with_subelements:
    #    - "{{ mariadb_database }}"
    #  run_once: true
    #  no_log: true
    #    #when: "'db_lbal_servers' in groups.keys()"

- name: Create a new MySQL user called monitor
  mysql_user:
    name: "monitor"
    host: "%"
    password: "{{ db_monitor_passwd | default('MonitoringPassword') }}"
    priv: "*.*:USAGE"
    state: "present"
    append_privs: "no"
    encrypted: "{{ mariadb_user_encrypted | default('no') }}"
    login_unix_socket: "{{ mariadb_socket }}"
  run_once: true
  no_log: true
    #when: "'db_lbal_servers' in groups.keys()" 

  #- name: Read SQL configuration
  #  set_fact:
  #    sql_content: "{{ lookup('template', '{{ role_path }}/templates/grant_all_hosts.sql.j2') }}"
  #  with_items:
  #    - user: monitor
  #      host: localhost
  #
  #- name: Integration SQL configuration
  #  copy:
  #    dest: /tmp/file.sql
  #    content: '{{ sql_content }}'
  #
  #- name: Grant appdb for all servers
  #  shell: "mysql -u {{ mysql_root_username }} -p{{ mysql_root_password }} -h 127.0.0.1 < /tmp/file.sql"
  #  run_once: true
  #  no_log: true
  #  when: "'db_lbal_servers' in groups.keys()" 
  #
  #- name: Remove file
  #  file:
  #    path: /tmp/file.sql
  #    state: absent
