---
- name: Create ProxySQL Directory
  become: yes
  become_user: jingrow
  file:
    dest: /home/jingrow/proxysql
    state: directory

- name: Copy ProxySQL TLS (Private Key)
  copy:
    src: /home/jingrow/agent/tls/privkey.pem
    dest: /home/jingrow/proxysql/proxysql-key.pem
    mode: 0600
    remote_src: yes

- name: Copy ProxySQL TLS (CA Certificate)
  copy:
    src: /home/jingrow/agent/tls/chain.pem
    dest: /home/jingrow/proxysql/proxysql-ca.pem
    mode: 0600
    remote_src: yes

- name: Copy ProxySQL TLS (Server Certificate)
  copy:
    src: /home/jingrow/agent/tls/fullchain.pem
    dest: /home/jingrow/proxysql/proxysql-cert.pem
    mode: 0600
    remote_src: yes

- name: Create ProxySQL config
  template:
    src: proxysql.cnf
    dest: /home/jingrow/proxysql/proxysql.cnf
    mode: 0644

- name: Start ProxySQL
  become: yes
  become_user: jingrow
  command: "docker run -d --name proxysql --hostname proxysql --restart always -p 3306:6033 -p 127.0.0.1:6032:6032 -p 127.0.0.1:6070:6070 -v /home/jingrow/proxysql:/var/lib/proxysql -v /home/jingrow/proxysql/proxysql.cnf:/etc/proxysql.cnf proxysql/proxysql:2.3.2"

- name: Update APT Cache
  apt:
    update_cache: yes

- name: Install MariaDB Client
  apt:
    pkg:
      - mariadb-client
      - python3-mysqldb
    state: present

- name: Enable ProxySQL Auditing
  mysql_query:
    login_user: jingrow
    login_password: "{{ proxysql_admin_password }}"
    login_host: 127.0.0.1
    login_port: 6032
    query:
      - INSERT INTO mysql_query_rules(active, match_digest, log) VALUES (1, '.', 1);
      - LOAD MYSQL QUERY RULES TO RUNTIME;
      - SAVE MYSQL QUERY RULES TO DISK;

- name: Setup Agent ProxySQL
  become: yes
  become_user: jingrow
  command: "/home/jingrow/agent/env/bin/agent setup proxysql --password {{ proxysql_admin_password }}"
  args:
    chdir: /home/jingrow/agent
