- name: Install MariaDB packages
  apt:
    name: mariadb-server
    state: present
    #install_recommends: no

- name: Ensure required directories exist
  file:
    path: "{{ item.path }}"
    state: directory
    owner: "{{ item.owner }}"
    group: "{{ item.group }}"
    mode: "{{ item.mode }}"
  loop:
    - { path: /var/log/mysql, owner: mysql, group: adm, mode: 'u=rwx,g=rxs,o=' }
    - { path: /root/scripts, owner: root, group: root, mode: 'u=rwx,g=rx,o=rx' }
    - { path: /mnt/mysqlbin, owner: root, group: root, mode: 'u=rwx,g=rx,o=rx' }
    - { path: /etc/systemd/system/mariadb.service.d, owner: root, group: root, mode: 'u=rwx,g=rx,o=rx' }
    - { path: /mnt/mysqltmp, owner: root, group: root, mode: 'u=rwx,g=rwx,o=rwxt' }
    - { path: /mnt/mysqlbin/binlog, owner: mysql, group: mysql, mode: 'u=rwx,g=,o=' }

- name: Set MariaDB custom configuration
  copy:
    src: "{{ item }}"
    dest: /etc/mysql/mariadb.conf.d/
    owner: root
    group: root
    mode: u=rw,g=r,o=r
  with_fileglob:
      - "files/z9*.cnf"
  notify: restart-mariadb

- name: Set MariaDB custom root scripts
  copy:
    src: "{{ item }}"
    dest: /root/scripts/
    owner: root
    group: root
    mode: u=rwx,g=rx,o=rx
  with_fileglob:
      - "files/scripts/*.sh"

- name: Ensure required files are copied to their destinations
  ansible.builtin.copy:
    src: "{{ item.src }}"
    dest: "{{ item.dest }}"
    owner: root
    group: root
    mode: "{{ item.mode }}"
  loop:
    - { src: 'files/scripts/README.md', dest: '/root/scripts/README.md', mode: 'u=rw,g=r,o=r' }
    - { src: 'mariadb_override.conf', dest: '/etc/systemd/system/mariadb.service.d/override.conf', mode: 'u=rw,g=r,o=r' }
    - { src: 'files/scripts/mysqltuner.pl', dest: '/root/scripts/mysqltuner.pl', mode: 'u=rwx,g=rx,o=rx' }
  notify:
    - reload systemd

#- name: Set MariaDB Cron to /etc/cron.d
#  template:
#    src: templates/cron_mariadb
#    dest: /etc/cron.d/vn
#    owner: root
#    group: root
#    mode: u=rw,g=r,o=r

- name: Add tmpfs in /etc/fstab
  blockinfile:
    path: /etc/fstab
    marker: "# {mark} ANSIBLE-MANAGED TMPFS ENTRY"
    block: |
      tmpfs /mnt/mysqltmp         tmpfs rw,size=6144M         0 0

- name: Insert MySQL certificates
  copy:
    content: "{{ item.content }}"
    dest: "{{ item.dest }}"
    owner: mysql
    group: mysql
    mode: "{{ item.mode }}"
  loop:
    - { content: '{{ ca_mysql }}', dest: '/etc/mysql/ca.pem', mode: 'u=rw,g=r,o=r' }
    - { content: '{{ cert_mysql }}', dest: '/etc/mysql/cert.pem', mode: 'u=rw,g=r,o=r' }
    - { content: '{{ private_mysql }}', dest: '/etc/mysql/key.pem', mode: 'u=rw,g=,o=' }