---
- name: Create MySQL Exporter Directory
  file:
    path: /opt/mysqld_exporter
    state: directory
    mode: 0755

- name: Set Architecture
  set_fact:
    arch: "{{'amd64' if (ansible_architecture == 'x86_64') else 'arm64'}}"

- name: Download MySQL Exporter Archive
  unarchive:
    src: "https://github.com/prometheus/mysqld_exporter/releases/download/v0.15.1/mysqld_exporter-0.15.1.linux-{{ arch }}.tar.gz"
    dest: /tmp
    remote_src: yes

- name: Copy MySQL Exporter Binary
  copy:
    src: "/tmp/mysqld_exporter-0.15.1.linux-{{ arch }}/mysqld_exporter"
    dest: /opt/mysqld_exporter/mysqld_exporter
    remote_src: yes
    mode: 0755
    owner: root
    group: root

- name: Create MySQL Client Config
  template:
    src: monitor.cnf
    dest: /home/jingrow/proxysql/monitor.cnf
    owner: root
    group: root
    mode: 0644

- name: Remove ProxySQL Monitor User
  mysql_query:
    login_user: jingrow
    login_password: "{{ proxysql_admin_password }}"
    login_host: 127.0.0.1
    login_port: 6032
    query:
      - DELETE FROM mysql_users WHERE username = "monitor"
      - LOAD MYSQL USERS TO RUNTIME
      - SAVE MYSQL USERS FROM RUNTIME
      - SAVE MYSQL USERS TO DISK


- name: Create ProxySQL Monitoring User
  mysql_query:
    login_user: jingrow
    login_password: "{{ proxysql_admin_password }}"
    login_host: 127.0.0.1
    login_port: 6032
    query:
      - "INSERT INTO mysql_users (username, password, default_hostgroup, default_schema, use_ssl, max_connections) VALUES ('monitor', 'monitor', {{ default_hostgroup }}, NULL, 1, 16)"
      - LOAD MYSQL USERS TO RUNTIME
      - SAVE MYSQL USERS FROM RUNTIME
      - SAVE MYSQL USERS TO DISK

- name: Create MySQL Exporter Systemd Service File
  template:
    src: mysqld_exporter.service
    dest: /etc/systemd/system/mysqld_exporter.service
    owner: root
    group: root
    mode: 0644

- name: Restart MySQL Exporter Service
  systemd:
    daemon_reload: true
    name: mysqld_exporter
    enabled: yes
    state: restarted
