---
- name: Manage the letsencrypt configuration
  block:
  - name: Check if the letsencrypt certificates are in place
    stat: path={{ letsencrypt_acme_certs_dir }}/privkey
    register: letsencrypt_keyfile

  - name: Copy the letsencrypt certificate key into the right place
    copy: src={{ letsencrypt_acme_certs_dir }}/privkey dest=/var/lib/mysql/client-key.pem owner=mysql group=mysql mode=0400 remote_src=yes force=yes
    when: letsencrypt_keyfile.stat.exists is defined and letsencrypt_keyfile.stat.exists | bool
    notify: Restart mysql 

  - name: Copy the letsencrypt public certificate into the right place
    copy: src={{ letsencrypt_acme_certs_dir }}/cert dest=/var/lib/mysql/client-cert.pem owner=mysql group=mysql mode=0444 remote_src=yes force=yes
    when: letsencrypt_keyfile.stat.exists is defined and letsencrypt_keyfile.stat.exists | bool
    notify: Restart mysql 

  - name: Copy the letsencrypt CA certificate into the right place
    copy: src={{ letsencrypt_acme_certs_dir }}/fullchain dest=/var/lib/mysql/ca.pem owner=mysql group=mysql mode=0444 remote_src=yes force=yes
    when: letsencrypt_keyfile.stat.exists is defined and letsencrypt_keyfile.stat.exists | bool
    notify: Restart mysql 

  - name: Create the acme hooks directory if it does not yet exist
    file: dest={{ letsencrypt_acme_sh_services_scripts_dir }} state=directory owner=root group=root

  - name: Install a script that fix the letsencrypt certificate for mysql and then reload the service
    copy: src=letsencrypt-mysql-hook.sh dest={{ letsencrypt_acme_sh_services_scripts_dir }}/mysql owner=root group=root mode=4555

  when: letsencrypt_acme_sh_install is defined and letsencrypt_acme_sh_install | bool
  tags: [ 'mysql', 'mariadb', 'letsencrypt', 'mysql_letsencrypt' ]