---
# file: roles/mysql/tasks/main.yml

- name: ensure mysql packages are installed
  apt:
    name:
      - mariadb-server
      - python3-mysqldb
    state: present
  tags:
    - packages
    - mysql

- name: ensure legacy mysql packages are installed
  apt:
    name:
      - python-mysqldb
    state: present
  when: ansible_distribution_major_version|int(default=99) < 11

- name: ensure mysql is started
  service:
    name: mysql
    state: started
    enabled: true

- name: setup mysql backups with rsnapshot
  when: mysql_rsnapshot
  block:
    - name: ensure a read-only mysql user for backups exists
      mysql_user:
        name: "{{ mysql_backup_user }}"
        password: "{{ mysql_backup_password }}"
        priv: "*.*:SELECT,LOCK TABLES,SHOW VIEW,TRIGGER"
      no_log: true

    - name: ensure the backup procedure can access the backup password
      template:
        src: my.cnf
        dest: "/root/.mysql-{{ mysql_backup_user }}.cnf"
        owner: root
        group: root
        mode: '0600'

    - name: deploy the mysql backup script
      template:
        src: mysqlbackup.sh
        dest: /usr/local/bin/
        owner: root
        group: root
        mode: '0755'

    - name: ensure we backup all the mysql databases with rsnapshot
      copy:
        src: rsnapshot.conf
        dest: /etc/rsnapshot.d/mysql.conf
        owner: root
        group: root
        mode: '0644'

    - name: remove obsolete crontab
      file:
        path: /etc/cron.d/mysql-snapshot
        state: absent
