---
- name: Determine certificate name
  ansible.builtin.set_fact:
    cert_item_name: "{{ cert_item.name | default(cert_item.domains | first | replace('*.', '')) }}"

- name: Check if certificate already exists.
  ansible.builtin.stat:
    path: /etc/letsencrypt/live/{{ cert_item_name }}/cert.pem
  register: letsencrypt_cert

- name: Create webroot directory if it doesn't exist yet
  ansible.builtin.file:
    path: "{{ cert_item.webroot | default(certbot_webroot) }}"
    state: directory

- name: Check if domains have changed
  when: letsencrypt_cert.stat.exists

  block:
    - name: Register certificate domains
      ansible.builtin.shell: "{{ certbot_script }} certificates --cert-name {{ cert_item_name }} | grep Domains | cut -d':' -f2"
      changed_when: false
      register: letsencrypt_cert_domains_dirty

    - name: Cleanup domain list
      ansible.builtin.set_fact:
        letsencrypt_cert_domains: "{{ letsencrypt_cert_domains_dirty.stdout | trim | split(' ') | map('trim') | select('!=', '') | list | sort }}"

    - name: Determine if domains have changed
      ansible.builtin.set_fact:
        letsencrypt_cert_domains_changed: "{{ letsencrypt_cert_domains != (cert_item.domains | map('trim') | select('!=', '') | list | sort) }}"

- name: Generate new certificate if one doesn't exist.
  ansible.builtin.command: "{{ certbot_create_command }}"
  when: not letsencrypt_cert.stat.exists or letsencrypt_cert_domains_changed | default(false)
