---
#
# Tasks related to setting up Let's Encrypt's management of certificates
#

- when: "matrix_ssl_retrieval_method == 'lets-encrypt'"
  block:
    - when: matrix_ssl_orphaned_renewal_configs_purging_enabled | bool
      ansible.builtin.import_tasks: "{{ role_path }}/tasks/ssl/purge_ssl_lets_encrypt_orphaned_configs.yml"

    - name: Ensure certbot Docker image is pulled
      community.docker.docker_image:
        name: "{{ matrix_ssl_lets_encrypt_certbot_docker_image }}"
        source: "{{ 'pull' if ansible_version.major > 2 or ansible_version.minor > 7 else omit }}"
        force_source: "{{ matrix_ssl_lets_encrypt_certbot_docker_image_force_pull if ansible_version.major > 2 or ansible_version.minor >= 8 else omit }}"
        force: "{{ omit if ansible_version.major > 2 or ansible_version.minor >= 8 else matrix_ssl_lets_encrypt_certbot_docker_image_force_pull }}"

    - name: Obtain Let's Encrypt certificates
      ansible.builtin.include_tasks: "{{ role_path }}/tasks/ssl/setup_ssl_lets_encrypt_obtain_for_domain.yml"
      with_items: "{{ matrix_ssl_domains_to_obtain_certificates_for | unique }}"
      loop_control:
        loop_var: domain_name

    - name: Ensure Let's Encrypt SSL renewal script installed
      ansible.builtin.template:
        src: "{{ role_path }}/templates/bin/lets-encrypt-certificates-renew.j2"
        dest: "{{ matrix_ssl_bin_dir_path }}/lets-encrypt-certificates-renew"
        mode: 0755

    - name: Ensure SSL renewal systemd units installed
      ansible.builtin.template:
        src: "{{ role_path }}/templates/systemd/{{ item.name }}.j2"
        dest: "{{ devture_systemd_docker_base_systemd_path }}/{{ item.name }}"
        mode: 0644
      when: "item.applicable | bool"
      with_items: "{{ matrix_ssl_renewal_systemd_units_list }}"

#
# Tasks related to getting rid of Let's Encrypt's management of certificates
#

- when: "matrix_ssl_retrieval_method != 'lets-encrypt'"
  block:
    - name: Ensure matrix-ssl-lets-encrypt-renew cronjob removed
      ansible.builtin.file:
        path: "{{ devture_systemd_docker_base_systemd_path }}/{{ item.name }}"
        state: absent
      when: "not item.applicable | bool"
      with_items: "{{ matrix_ssl_renewal_systemd_units_list }}"

    - name: Ensure Let's Encrypt SSL renewal script removed
      ansible.builtin.file:
        path: "{{ matrix_ssl_bin_dir_path }}/lets-encrypt-certificates-renew"
        state: absent
