- name: "Include flavor"
  include_tasks: "{{ role_path }}/tasks/flavors/{{ certbot_flavor }}.yml"

#- name: "Cleanup dedicated cert for {{ domain }}"
#  command: >-
#    certbot delete --cert-name {{ domain }} --non-interactive
#  when: 
#    - mode_cleanup | bool
#      # Cleanup mode is enabled
#    - certbot_flavor != 'dedicated'
#      # Wildcard certificate is enabled
#    - domain.split('.') | length == (primary_domain.split('.') | length + 1) and domain.endswith(primary_domain)
#      # AND: The domain is a direct first-level subdomain of the primary domain
#    - domain != primary_domain  
#      # The domain is not the primary domain
#  register: certbot_result
#  failed_when: certbot_result.rc != 0 and ("No certificate found with name" not in certbot_result.stderr)
#  changed_when: certbot_result.rc == 0 and ("No certificate found with name" not in certbot_result.stderr)

- name: Find SSL cert folder for domain
  cert_folder_find:
    domain: "{{ domain }}"
    cert_base_path: "{{ certbot_cert_path }}"
    debug: "{{ enable_debug | default(false) }}"
  register: cert_folder_result
  delegate_to: "{{ inventory_hostname }}"
  changed_when: false

- name: Set fact
  set_fact:
    ssl_cert_folder: "{{ cert_folder_result.folder }}"
  changed_when: false

- name: Ensure ssl_cert_folder is set
  fail:
    msg: "No certificate folder found for domain {{ domain }}"
  when: ssl_cert_folder is undefined or ssl_cert_folder is none